[英]why output list is empty in my code in Python 2.7
使用 Python 2.7 并尝试对 UTF-8 编码文件进行简单的标记化。 的输出a
似乎字节串,这是意料之中的,因为后tk[0].encode('utf-8')
它从转换的Python unicode
类型到str/byte
。 我的主要困惑是为什么b
输出是空列表? 我认为没有编码(我的意思是没有调用.encode('utf-8')
),它应该是原始 unicode 字符(例如,我希望打印一些汉字,因为1.txt
是 UTF-8 编码的汉字文件)。
源代码,
import jieba
if __name__ == "__main__":
with open('1.txt', 'r') as content_file:
content = content_file.read()
segment_list = jieba.tokenize(content.decode('utf-8'), mode='search')
if segment_list is None:
print 'segment is None'
else:
a = [tk[0].encode('utf-8') for tk in segment_list]
b = [tk[0] for tk in segment_list]
print a
print b
** 输出 **,
['\xe4\xb8\x8a\xe6\xb5\xb7', '\xe6\xb5\xb7\xe5\xb8\x82', '\xe4\xb8\x8a\xe6\xb5\xb7\xe5\xb8\x82', '\xe6\xb7\xb1\xe5\x9c\xb3', '\xe6\xb7\xb1\xe5\x9c\xb3\xe5\xb8\x82', '\xe7\xa6\x8f\xe7\x94\xb0', '\xe7\xa6\x8f\xe7\x94\xb0\xe5\x8c\xba', '\xe6\xa2\x85\xe6\x9e\x97', '\xe6\x9e\x97\xe8\xb7\xaf', '\xe6\xa2\x85\xe6\x9e\x97\xe8\xb7\xaf', '\xe4\xb8\x8a\xe6\xb5\xb7', '\xe6\xb5\xb7\xe5\xb8\x82', '\xe6\xb5\xa6\xe4\xb8\x9c', '\xe6\x96\xb0\xe5\x8c\xba', '\xe4\xb8\x8a\xe6\xb5\xb7\xe5\xb8\x82', '\xe4\xb8\x8a\xe6\xb5\xb7\xe5\xb8\x82\xe6\xb5\xa6\xe4\xb8\x9c\xe6\x96\xb0\xe5\x8c\xba', '\xe8\x80\x80\xe5\x8d\x8e', '\xe8\xb7\xaf', '\r\n']
[]
看来jieba.tokenize()
返回一个生成器。 一个生成器只能迭代一次。 最好做
b = [tk[0] for tk in segment_list]
a = [tk.encode('utf-8') for tk in b]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.