Python 解码中文stopwords文件并添加到列表
我正在尝试读取中文stopwords文件,并将字符附加到列表中。这是我的代码:Python 解码中文stopwords文件并添加到列表,python,encoding,utf-8,decode,Python,Encoding,Utf 8,Decode,我正在尝试读取中文stopwords文件,并将字符附加到列表中。这是我的代码: word_list=[] with open("stop-words_chinese_1_zh.txt", "r") as f: for row in f: decoded=row.decode("utf-8") print decoded word_list.append(decoded) print word_list[:10] 这是我的输出。Decode
word_list=[]
with open("stop-words_chinese_1_zh.txt", "r") as f:
for row in f:
decoded=row.decode("utf-8")
print decoded
word_list.append(decoded)
print word_list[:10]
这是我的输出。Decoded看起来不错,但在我将Decoded附加到列表后,它会恢复为未编码的字符
着
诸
自
[u'\u7684\r\n', u'\u4e00\r\n', u'\u4e0d\r\n', u'\u5728\r\n', u'\u4eba\r\n', u'\u6709\r\n', u'\u662f\r\n', u'\u4e3a\r\n', u'\u4ee5\r\n', u'\u4e8e\r\n']
列表尚未恢复为未编码的字符。如果打印列表中元素的类型: 打印类型(单词列表[0]) 你会得到:
所以你的清单没有任何问题。现在我们将注意力转向打印功能。在对象上调用print时,它将打印该对象的str函数返回的任何内容。但是,对于列表,其str函数对每个元素迭代调用repr,从而返回所述元素的Python表示字符串
这里需要的行为是对列表中的每个元素调用str,而不是repr。这里有一个警告:str将尝试使用“ascii”编码对给定对象进行编码,由于列表元素采用unicode编码,因此该编码总是会失败。为了在屏幕上显示,您可能需要sys.stdout.encoding,它通常是“UTF-8”
因此,要在屏幕上打印unicode列表:
>>> import sys
>>> print '[' + ','.join(w.encode(sys.stdout.encoding) for w in word_list) + ']'
或者,我们可以传入unicode字符串,让print处理屏幕上的编码:
>>> print u'[' + u','.join(word_list) + u']'
最后一件事:word_列表中的元素似乎也包含换行符。你可能想省略它们,因为你正在建立一个停止词的列表。您的最终解决方案是:
>>> print u'[' + u','.join(w[0] for w in word_list) + u']'