我用nltk的CategorizedPlaintextCorpusReader
创建了一个自定义语料库。在
在我的语料库的.txt文件中有一些unicode字符,我无法解码。我认为这是一个事实,这是一个“明文”阅读器,但仍然需要解码。在
代码:
import nltk
from nltk.corpus import CategorizedPlaintextCorpusReader
import os
mr = CategorizedPlaintextCorpusReader('C:\mycorpus', r'(?!\.).*\.txt',
cat_pattern=os.path.join(r'(neg|pos)', '.*',))
for w in mr.words():
print(w)
这将以标记格式打印不包含unicode的文件的单词,然后引发以下错误:
^{pr2}$我试图用以下方法解码:
mr.decode('unicode-escape')
会引发以下错误:
AttributeError: 'CategorizedPlaintextCorpusReader' object has no attribute 'decode'
我使用的是python3.6.4。在
问题是NLTK的语料库阅读器假设您的纯文本文件是用UTF-8编码保存的。 然而,这个假设显然是错误的,因为文件是用另一个编解码器编码的。 我的猜测是使用了CP1252(又名“Windows拉丁语-1”),因为它非常流行,而且很适合您的描述:在这种编码中,em破折号“–”是用字节
0x96
编码的,这在错误消息中提到过。在您可以在语料库读取器的构造函数中指定输入文件的编码:
试试这个,然后检查输出中的非ASCII字符(em dash、bullet)是否仍然正确(并且没有被mojibake替换)。在
相关问题 更多 >
编程相关推荐