如何在不同的字符串表示形式之间的转换中使用Tensorflow?

可以使用“解码”方法将编码后的字符串标量转换为代码点向量。可以使用“ encode”方法将代码点的向量转换为编码的字符串标量。可以使用“转码”方法将编码后的字符串标量转换为其他编码。

阅读更多:什么是TensorFlow,以及Keras如何与TensorFlow一起创建神经网络?

让我们了解如何使用Python表示Unicode字符串,以及如何使用Unicode等效项操纵它们。首先,借助于标准字符串操作的Unicode等效项,我们基于脚本检测将Unicode字符串分成令牌。

我们正在使用Google合作实验室来运行以下代码。Google Colab或Colaboratory可以帮助通过浏览器运行Python代码,并且需要零配置和对GPU(图形处理单元)的免费访问。合作已建立在Jupyter Notebook的基础上。

print("Converting encoded string scalar to a vector of code points")
tf.strings.unicode_decode(text_utf8,input_encoding='UTF-8')
print("Converting vector of code points to an encoded string scalar")
tf.strings.unicode_encode(text_chars, output_encoding='UTF-8')
print("Converting encoded string scalar to a different encoding")
tf.strings.unicode_transcode(text_utf8, input_encoding='UTF8', output_encoding='UTF-16-BE')

代码信用:https://www.tensorflow.org/tutorials/load_data/unicode

输出结果

Converting encoded string scalar to a vector of code points
Converting vector of code points to an encoded string scalar
Converting encoded string scalar to a different encoding
<tf.Tensor: shape=(), dtype=string, numpy=b'\x8b\xed\x8a\x00Y\x04t\x06'>

解释

  • 函数“ unicode_decode”用于将编码的字符串标量转换为代码点的向量。

  • 函数“ unicode_encode”用于将代码点的向量转换为编码的字符串标量。

  • 函数“ unicode_transcode”用于将编码的字符串标量转换为不同的编码。

猜你喜欢