中世纪字符的UnicodeDecodeError

时间:2015-05-12 15:09:53

标签: python unicode encoding utf-8 nltk

我正在尝试在中世纪文本上运行nltk tokenize程序。这些文本使用中世纪字符,如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)

1 个答案:

答案 0 :(得分:1)

您的文件无效UTF-8。

也许它部分是UTF-8,部分是其他垃圾?你可以尝试:

open(..., encoding='utf-8', errors='replace')

用问号替换非UTF-8序列而不是引发错误,这可能会让您有机会看到问题所在。一般来说,如果你在一个文件中混合使用各种编码,那么你几乎注定要失败,因为它们无法被可靠地分开。