Tensorflow string tf.print和编码问题

如果直接 tf.print(textbody), 这里 textbody 是 tf.string 类型, 会得到:\350\257\225\350\241\243\351\227\264\347\251\277\346\220\255\346\214\221\346\210\230[SEP]

原因是 tf.string 既不是 string 也不是 bytes 类型,想要看原来的中文,要注意转成 string 格式。
如果需要处理可以通过 pyfunction 转为 string 然后处理

tf.py_func(xxxx_func, [textbody], (tf.string)), 其中 xxxx_func 是处理 string 的 python 代码 ,可以在 xxxx_func 内部进行print 此时就是正常的 string了;注意这时 tf.py_func 输出的已经是 tensor [1] 了,后续格式不需要额外再加 [], 否则会变成 [1, 1].

xxxx_function 还可能遇到python2, python3 编码的坑,可以参考:Py2, py3 编码的差异

在 xxxx_function 里想要规避这个编码的坑,可以通过这个函数:

def convert_to_unicode(text):
    """Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
    if six.PY3:
        if isinstance(text, str):
            return text
        elif isinstance(text, bytes):
            return text.decode("utf-8", "ignore")
        else:
            raise ValueError("Unsupported string type: %s" % (type(text)))
    elif six.PY2:
        if isinstance(text, str):
            return text.decode("utf-8", "ignore")
        elif isinstance(text, unicode):
            return text
        else:
            raise ValueError("Unsupported string type: %s" % (type(text)))
    else:
        raise ValueError("Not running on Python2 or Python 3?")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值