【问题标题】:Traceback error when reading file in python在python中读取文件时出现回溯错误
【发布时间】:2018-02-12 00:13:01
【问题描述】:

我目前正在学习Python,遇到以下错误:

回溯(最近一次通话最后一次):
文件“file.py”,第 22 行,在模块中

file.read() 中的单词:

文件 "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\encodings\cp1252.py", 第 23 行,在解码中

返回 codecs.charmap_decode(input,self.errors,decoding_table)[0]

UnicodeDecodeError: 'charmap' 编解码器无法在位置解码字节 0x9d 6552: 字符映射到未定义

这是我的代码:

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)

有人知道为什么会这样吗?

提前致谢!

【问题讨论】:

标签: python django python-unicode traceback


【解决方案1】:

您能否通过指定编码尝试进行此更改:

file=open('xyz.txt', encoding='utf8')

ignorelist 文件可能也需要它)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 2020-10-11
    相关资源
    最近更新 更多