【问题标题】:String processing error: UnicodeDecodeError: 'utf8' codec can't decode字符串处理错误:UnicodeDecodeError: 'utf8' codec can't decode
【发布时间】:2012-04-11 21:18:01
【问题描述】:

我正在尝试分析一系列密码的频率。我的脚本正在使用其他输入媒体,但是在我当前的数据集中似乎有一些坏字符。如何绕过“坏”数据?

import re
import collections 
words = re.findall('\w+', open('rockyou.txt').read().lower())
a=collections.Counter(words).most_common(50)
for word in a:
     print(word)

然后我得到错误:

Traceback (most recent call last):
  File "shakecount.py", line 3, in <module>
    words = re.findall('\w+', open('rockyou.txt').read().lower().ASCII)
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/codecs.py", line 300, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xf1 in position 5079963: invalid continuation byte

有什么想法吗?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    您的代码与您的错误不完全匹配(我假设尝试调试?),但您的文本文件不是 UTF-8

    您需要手动指定编码,我的最佳猜测是latin-1

    words = re.findall('\w+', open('rockyou.txt', encoding='latin-1').read().lower())
    

    如果您想在出现错误的情况下继续,可以将errors='ignore'errors='replace' 传递给open

    【讨论】:

    • 以上内容很有帮助,但并没有最终解决问题,我遇到了更多希腊错误(我是编程新手)。我最终在文本编辑器中打开了单词列表,并将其重新保存为 utf-8 格式,然后就可以使用了。感谢 agf 的帮助!
    • @AlphaTested 如果您不知道编码,另一种方法是使用chardet 来检测它。
    猜你喜欢
    • 2014-09-27
    • 2014-05-14
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    相关资源
    最近更新 更多