Skip to main content
 首页 » 编程设计

python之具有 unicode 类型,但应为 :bytes tf. train.example 之一

2024年10月01日652php

当我制作 tfrecords 文件时,假设写入了 unicode 字符串,将会出现错误:TypeError: u'\u634f' has type unicode but expected one of :bytes

writer = tf.python_io.TFRecordWriter(tfrecords_output_filename) text=u'地离开对方' 示例 = tf.train.Example(features=tf.train.Features(feature={'text':_bytes_feature([text])})) writer.write(example.SerializeToString()) writer.close()

但是英文和数字形式没问题:text='abcd123'
我该如何解决这个问题?

请您参考如下方法:

您必须使用 utf-8 而不是 unicode 对文本进行编码才能使其与字节兼容:

text=u'地离开对方' 
text = text.encode("utf8") 
example = tf.train.Example(features=tf.train.Features(feature={'text':_bytes_feature([text])}))