繁体   English   中英

python 3.5.2中的UnicodeDecodeError

[英]UnicodeDecodeError in function python 3.5.2

UnicodeDecodeError

def getWordFreqs(textPath, stopWordsPath):
    wordFreqs = dict()
    #open the file in read mode and open stop words
    file = open(textPath, 'r')
    stopWords = set(line.strip() for line in open(stopWordsPath))
    #read the text
    text = file.read()
    #exclude punctuation and convert to lower case; exclude numbers as well
    punctuation = set('!"#$%&\()*+,-./:;<=>?@[\\]^_`{|}~')
    text = ''.join(ch.lower() for ch in text if ch not in punctuation)
    text = ''.join(ch for ch in text if not ch.isdigit())
    #read through the words and add to frequency dictionary
    #if it is not a stop word
    for word in text.split():
        if word not in stopWords:
            if word in wordFreqs:
                wordFreqs[word] += 1
            else:
                wordFreqs[word] = 1

每当我尝试在python 3.5.2中运行此函数时,都会收到以下错误,但是在3.4.3中它可以正常工作,我无法弄清楚是什么原因导致了此错误。

line 9, in getWordFreqs
    text = file.read()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0x97 in position 520: ordinal not in range(128)

在Python 3中,默认open是使用locale.getpreferredencoding(False)返回的编码。 它通常不是ascii ,但是如果在某种错误消息指示的某种框架下运行则可以。

而是,指定要尝试读取的文件的编码。 如果文件是在Windows下创建的,则编码可能是cp1252 ,尤其是因为字节\\x97是该编码下的EM DASH

尝试:

file = open(textPath, 'r', encoding='cp1252')

我相信解决您问题的一种方法是将这段代码放在文件顶部。

import sys
reload(sys)
sys.setdefaultencoding("UTF8")

这会将编码设置为UTF8

另一个(更好的)解决方案是一个称为编解码器的库,该库非常易于使用。

import codecs
fileObj = codecs.open( "someFile", "r", "utf-8" )

然后,fileObj是可以读取和写入的普通文件对象。

方法1的 来源方法2的来源

方法1的注意事项
当使用使用ASCII作为其编码的第三方应用程序时,这可能非常危险。 请谨慎使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM