如何使用Tensorflow和Python将Unicode字符串表示为UTF-8编码的字符串?

如何使用Tensorflow和Python将Unicode字符串表示为UTF-8编码的字符串?

一组Unicode字符串可以使用“encode”方法表示为UTF8编码的字符串。

处理自然语言的模型处理具有不同字符集的不同语言。 Unicode被认为是用于表示几乎所有语言的标准编码系统。每个字符都使用介于0和0x10FFFF之间的唯一整数码点进行编码。 Unicode字符串是零个或多个代码值的序列。

让我们了解如何使用Python表示Unicode字符串,并使用Unicode等效物来操作。首先,我们基于Unicode等效物的标准字符串操作将Unicode字符串分为标记。

我们使用Google Colaboratory来运行以下代码。 Google Colab或Colaboratory可以在浏览器上运行Python代码,无需任何配置并且免费访问GPU(图形处理单元)。 Colaboratory是基于Jupyter Notebook构建的。

print("A set of Unicode strings which is represented as a UTF8-encoded string")
batch_utf8 = [s.encode('UTF-8') for s in[u'hÃllo',   u'What is the weather tomorrow',u'Göödnight', u'😊']]
batch_chars_ragged = tf.strings.unicode_decode(batch_utf8,
input_encoding='UTF-8')
for sentence_chars in batch_chars_ragged.to_list():
   print(sentence_chars)
print("Dense tensor with padding are printed")
batch_chars_padded = batch_chars_ragged.to_tensor(default_value=-1)
print(batch_chars_padded.numpy())
print("Converting to sparse matrix")
batch_chars_sparse = batch_chars_ragged.to_sparse()

代码来源:https://www.tensorflow.org/tutorials/load_data/unicode

阅读更多:Python 教程

输出

A set of Unicode strings which is represented as a UTF8-encoded string
[104, 195, 108, 108, 111]
[87, 104, 97, 116, 32, 105, 115, 32, 116, 104, 101, 32, 119, 101, 97, 116, 104, 101, 114, 32, 116, 111, 109, 111, 114, 114, 111, 119]
[71, 246, 246, 100, 110, 105, 103, 104, 116]
[128522]
Dense tensor with padding are printed
[[ 104      195      108      108      111       -1       -1       -1       -1       -1
   -1       -1       -1       -1       -1       -1       -1       -1       -1       -1
   -1       -1       -1       -1       -1       -1       -1       -1]
[87      104       97      116       32      105      115       32      116      104
 101       32      119      101       97      116      104      101      114       32
 116      111      109      111      114      114      111      119]
[71      246      246      100      110      105      103      104      116       -1
   -1       -1       -1       -1       -1       -1       -1       -1       -1       -1
   -1       -1       -1       -1       -1       -1       -1       -1]
[128522       -1       -1      -1       -1       -1       -1       -1       -1       -1]]
转换为稀疏矩阵

解释

  • 当多个字符串被解码时,每个字符串中的字符数可能不相等。
  • 结果将是tf.RaggedTensor,在这里内部维度的长度变化,并且该变化取决于每个字符串中字符的数量。
  • 此tf.RaggedTensor可以直接使用,或者可以使用方法tf.RaggedTensor.to_tensor将其转换为具有填充的密集tf.Tensor,或者使用tf.RaggedTensor.to_sparse转换为tf.SparseTensor。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程