读取 python 中的文件时出现回溯错误
Traceback error when reading file in python
我目前正在学习 Python 并遇到以下错误:
Traceback (most recent call last):
File "file.py", line 22, in module
for word in file.read():
File
"C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\encodings\cp1252.py",
line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position
6552: character maps to undefined
这是我的代码:
file=open('xyz.txt')
dict={}
ignorelist=set( line.strip() for line in open('ignorelist'))
for word in file.read():
word = word.replace(".","")
word = word.replace(",","")
if word not in ignorelist:
if word not in dict:
dict[word] = 1
else:
dict[word] += 1
d=collections.Counter(dict)
for word, count in d.most_common(10):
print(word, ": ", count)
有人知道为什么会这样吗?
提前致谢!
您能否通过指定编码尝试进行此更改:
file=open('xyz.txt', encoding='utf8')
(ignorelist
文件可能也需要它)
我目前正在学习 Python 并遇到以下错误:
Traceback (most recent call last):
File "file.py", line 22, in modulefor word in file.read():
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 6552: character maps to undefined
这是我的代码:
file=open('xyz.txt')
dict={}
ignorelist=set( line.strip() for line in open('ignorelist'))
for word in file.read():
word = word.replace(".","")
word = word.replace(",","")
if word not in ignorelist:
if word not in dict:
dict[word] = 1
else:
dict[word] += 1
d=collections.Counter(dict)
for word, count in d.most_common(10):
print(word, ": ", count)
有人知道为什么会这样吗?
提前致谢!
您能否通过指定编码尝试进行此更改:
file=open('xyz.txt', encoding='utf8')
(ignorelist
文件可能也需要它)