【问题标题】:why does it give UnicodeDecodeError?为什么它会给出 UnicodeDecodeError?
【发布时间】:2020-05-13 10:32:51
【问题描述】:

我正在学习关于 py4e 的 python 课程,几乎完成了,但第 11 章似乎不可能,因为它每次都会给我错误。

错误:

line 4, in <module>
    lines = ffail.read()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd1 in position 8: invalid continuation byte

代码:

import re

ffail = open('regex_sum_340933.txt')
lines = ffail.read()
count = 0

match = re.findall('[0-9]+', lines)

for II in match:
    number = int(II)
    count = count + number
print(count)

【问题讨论】:

标签: python-3.x file


【解决方案1】:

试试这个:

import re

lines = open('regex_sum_340933.txt', encoding='utf-8', errors='ignore').read()
count = sum(map(int, re.findall('[0-9]+', lines)))

【讨论】:

    【解决方案2】:

    你做得不对。首先你需要关闭我建议的文件

    只需使用with,因此您无需担心关闭文件。

    用这个替换你读取文件的方式

    ffail = ""
    with open("regex_sum_340933.txt", mode = "r" ,encoding='UTF-8', errors='ignore',  buffering=-1) as some_file:
        ffail = some_file.read()
    

    确保regex_sum_340933.txt 与代码文件位于同一目录中。

    如果您仍然遇到困难,可以访问question

    【讨论】:

    • 您能否接受这个问题/解释为什么它不起作用以及问题出在哪里?
    • 代码应该是这样的吗? import re ffail = "" with open("regex_sum_340933.txt", "r" , "UTF-8") as some_file: ffail = some_file.read() count = 0 match = re.findall('[0-9] +', ffail) for II in match: number = int(II) count = count + number print(count) 给出此错误:第 4 行,在 中使用 open("regex_sum_340933.txt", "r" , " UTF-8") as some_file: TypeError: an integer is required (got type str).我不明白我需要做什么。
    • @RomeEsna 尝试用我无法理解的错误更新您的代码
    • with open("regex_sum_340933.txt", "r" , "UTF-8") as some_file: TypeError: an integer is required (got type str) 它给了我这个错误,有什么建议吗?
    • @RomeEsna 查看更新的答案尝试使用和不使用buffering 并显示错误(如果有)
    【解决方案3】:

    感谢您的帮助,代码没有错,只是我的 Mac 不想让它工作。用windows试了一下,马上就有答案了。

    【讨论】:

      猜你喜欢
      • 2018-07-01
      • 1970-01-01
      • 2017-06-03
      • 2023-03-03
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      相关资源
      最近更新 更多