tf.data 加载 Unicode 字符串

该博客介绍了如何利用tf.data在TensorFlow中加载和处理包含Unicode字符的数据。通过示例代码展示了具体操作,并给出了运行结果。
摘要由CSDN通过智能技术生成

Unicode 字符串

代码

# -*- coding: utf-8 -*-
"""
Created on  2020/11/23 10:27
@Author: CY
@email: 5844104706@qq.com
"""

'''
Unicode 是一种标准的编码系统,用于表示几乎所有语言的字符。每个字符使用 0 和 0x10FFFF 之间的唯一整数码位进行编码。
Unicode 字符串是由零个或更多码位组成的序列。
TensorFlow 中表示 Unicode 字符串,以及如何使用标准字符串运算的 Unicode 等效项对其进行操作。
它会根据字符体系检测将 Unicode 字符串划分为不同词例。
'''
import tensorflow as tf

# Unicode 字符串默认使用 UTF-8 编码
print(tf.constant(u"Thanks 😊"))
# 使用 Python 构造字符串时,v2 和 v3 对 Unicode 的处理方式有所不同。
##  在 v2 中,Unicode 字符串用前缀“u”表示(如上所示)。
##  在 v3 中,字符串默认使用 Unicode 编码。
tf.constant([u"You're", u"welcome!"]).shape

# 在 TensorFlow 中有两种表示 Unicode 字符串的标准方式:
## string 标量 - 使用已知字符编码对码位序列进行编码。
## int32  向量 - 每个位置包含单个码位。
text_utf8 = tf.constant(u"语言处理")
print(text_utf8)
# Unicode string, represented as a UTF-16-BE encoded string scalar.
text_utf16be = tf.constant(u"语言处理".encode("UTF-16-BE"))
print(text_utf16be)

text_chars = tf.constant([ord(char) for char in u"语言处理"])
print(text_chars)

## TensorFlow 提供了在下列不同表示之间进行转换的运算:
### tf.strings.unicode_decode:              将编码的字符串标量转换为码位的向量。
### tf.strings.unicode_encode:              将码位的向量转换为编码的字符串标量。
### tf.strings.unicode_transcode:           将编码的字符串标量转换为其他编码。
tf.strings.unicode_decode(text_utf8, input_encoding='UTF-8')
tf.strings.unicode_encode(text_chars, output_encoding='UTF-8')
tf.strings.unicode_transcode(text_utf8, input_encoding='UTF8', output_encoding='UTF-16-BE')

# 解码多个字符串时,每个字符串中的字符数可能不相等。
# 返回结果是 tf.RaggedTensor,其中最里面的维度的长度会根据每个字符串中的字符数而变化:
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ynchyong

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值