[英]UnicodeDecodeError when using a Python string handling function
[英]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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.