【发布时间】:2015-05-12 15:09:52
【问题描述】:
我正在尝试在中世纪文本上运行一个 nltk 标记程序。这些文本使用中世纪字符,例如 yogh (ȝ)、thorn (þ) 和 eth (ð)。
当我使用标准 unicode (utf-8) 编码运行程序(粘贴在下面)时,我收到以下错误:
Traceback (most recent call last):
File "me_scraper_redux2.py", line 11, in <module>
tokens = nltk.word_tokenize( open( "ME_Corpus_sm/"+file, encoding="utf_8" ).read() )
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/codecs.py", line 313, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 3131: invalid start byte
我尝试过其他编码,例如 latin1 等,这些都规避了这个问题,但是我没有得到准确的结果,因为这些编码使用其他字符来填充空间。我认为 unicode 可以处理这些字符。我做错了什么,还是我应该使用另一种编码?这些文件最初是 utf-8。 请参阅下面的代码:
import nltk
import os, os.path
import string
from nltk import word_tokenize
from nltk.corpus import stopwords
files = os.listdir("ME_Corpus_sm/")
for file in files:
# open, parse, and normalize the tokens (words) in the file
tokens = nltk.word_tokenize( open( "ME_Corpus_sm/"+file, encoding="utf_8" ).read() )
tokens = [ token.lower() for token in tokens ]
tokens = [ ''.join( character for character in token if character not in string.punctuation ) for token in tokens ]
tokens = [ token for token in tokens if token.isalpha() ]
tokens = [ token for token in tokens if not token in stopwords.words( 'english' ) ]
# output maximum most frequent tokens and their counts
for tuple in nltk.FreqDist( tokens ).most_common( 50 ):
word = tuple[ 0 ]
count = str( tuple[ 1 ] )
print(word + "\t" + count)
【问题讨论】:
-
您能否发布一段非常 小段的文本摘录,例如,包含一根刺(可能是所述摘录的二进制十六进制或base64 编码)?错误(“无效的起始字节 0x80”)似乎指向无效的 UTF-8,因为 0x80 是一个 10xxxxxx 字节,它应该是一个 continuation 代码,永远不会在令牌的开头找到.它可以在 ISO-8859-15 (Latin1) 文本中遇到,不过...
-
仅供参考 Unicode 不是 UTF-8。
-
马丁,谢谢你,我还在纠结这些事情!
-
lserni,感谢您的帮助。希望 bobince 的回复能让我们暂时不必检查二进制文件 :)
标签: python unicode encoding utf-8 nltk