解码中文停用词文件并附加到列表

decoding a chinese stopwords file and appending to a list

我正在尝试读取中文停用词文件并将字符附加到列表中。这是我的代码:

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]

这是我的输出。解码看起来不错,但在我将解码附加到列表后,它恢复为未解码的字符。

着

诸

自
[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']

列表没有还原为未解码的字符。如果打印列表中元素的类型:

>>> print type(word_list[0])

你会得到:

<type 'unicode'>

所以你的清单没有任何问题。现在我们将注意力转向打印功能。当您在一个对象上调用 print 时,它会打印该对象的 str 函数 returns 的任何内容。然而,在列表的情况下,它的 str 函数在每个元素上迭代调用 repr,returns 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_list 中的元素似乎也包含换行符。你可能想忽略它们,因为你正在构建一个停用词列表。您的最终解决方案是:

>>> print u'[' + u','.join(w[0] for w in word_list) + u']'