python - 可能导致此错误的原因:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 568: invalid start byte
问题描述
我对编码和 python 很陌生,所以我真的对这个错误感到困惑。这是我的练习代码,我需要在包含多个文件的目录中找到最常用的单词
import pathlib
directory = pathlib.Path('/Users/k/files/Code/exo')
stats ={}
for path in directory.iterdir():
file = open(str(path))
text = file.read().lower()
punctuation = (";", ".")
for mark in punctuation:
text = text.replace(mark, "")
for word in text.split():
if word in stats:
stats[word] = stats[word] + 1
else:
stats[word] = 1
most_used_word = None
score_max = 0
for word, score in stats.items():
if score > score_max:
score_max = score
most_used_word = word
print(word,"The most used word is : ", score_max)
这就是我得到的
Traceback (most recent call last):
File "test.py", line 9, in <module>
text = file.read().lower()
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 0xff in position 568: invalid start byte
什么可能导致此错误?
解决方案
可能您的文件包含非 ascii 字符,因此您必须对它们进行解码才能使 UnicodeDecodeError 消失。您可以尝试在“rb”模式下阅读,如下所示:
file = open(str(path), 'rb')
在 Windows 上,附加到模式的 'b' 以二进制模式打开文件,因此还有 'rb'、'wb' 和 'r+b' 等模式。Windows 上的 Python 区分了文本文件和二进制文件;读取或写入数据时,文本文件中的行尾字符会自动稍作更改。这种对文件数据的幕后修改适用于 ASCII 文本文件,但它会破坏 JPEG 或 EXE 文件中的二进制数据。在读写此类文件时要非常小心使用二进制模式。在 Unix 上,将“b”附加到模式并没有什么坏处,因此您可以独立于平台使用它来处理所有二进制文件。
(来自文档)
推荐阅读
- python - 我得到 a += b 的 TypeError,但不是 b += a (numpy)
- java - Android Studio - 如何从手机号码获取用户详细信息?
- google-assistant-sdk - 移动应用程序中的 Google 助理自定义命令
- android - Unity Camera 无法在 Android 上显示整个游戏屏幕(画布)
- ios - 登录屏幕后显示侧面菜单
- pandas - 如何使用逗号分隔值删除重复项和 dcast pandas 数据帧
- php - PHP 类对象作为其他类参数
- python - 将颜色条作为图例添加到 matplotlib 散点图(多个子图、多个散点图)
- wordpress - 如何在二十六主题的商店页面中添加过滤器
- jquery - 获取 contentEditable div 的第一行