如何使用Tensorflow在不同字符串表示之间进行转换?
使用“decode”方法可以将编码的字符串标量转换为代码点向量。可以使用“encode”方法将代码点向量转换为编码的字符串标量。可以使用“transcode”方法将编码的字符串标量转换为不同的编码。
阅读更多:什么是TensorFlow,以及如何使用TensorFlow来创建神经网络?
让我们了解如何使用Python表示Unicode字符串,并使用Unicode等效项处理这些字符串。首先,我们根据脚本检测将Unicode字符串分成标记,并借助标准字符串操作的Unicode等效项来操作。
我们使用Google Colaboratory来运行以下代码。Google Colab或Colaboratory可以通过浏览器运行Python代码,并且无需任何配置,可以免费访问GPU(图形处理单元)。 Colaboratory是基于Jupyter Notebook构建的。
print("将编码的字符串标量转换为代码点向量")
tf.strings.unicode_decode(text_utf8,input_encoding='UTF-8')
print("将代码点向量转换为编码的字符串标量")
tf.strings.unicode_encode(text_chars, output_encoding='UTF-8')
print("将编码的字符串标量转换为不同的编码")
tf.strings.unicode_transcode(text_utf8, input_encoding='UTF8', output_encoding='UTF-16-BE')
代码来源: https://www.tensorflow.org/tutorials/load_data/unicode
输出
将编码的字符串标量转换为代码点向量
将代码点向量转换为编码的字符串标量
将编码的字符串标量转换为不同的编码
<tf.Tensor: shape=(), dtype=string, numpy=b'\x8b\xed\x8a\x00Y\x04t\x06'>
解释
- 使用’unicode_decode’函数将编码的字符串标量转换为代码点向量。
- 使用’unicode_encode’函数将代码点向量转换为编码的字符串标量。
- 使用’unicode_transcode’函数将编码的字符串标量转换为不同的编码。
更多Python相关文章,请阅读:Python 教程
极客教程