gpt4 book ai didi

python - 读取文件时出现 UnicodeEncodeError

转载 作者:太空宇宙 更新时间:2023-11-03 16:30:33 24 4
gpt4 key购买 nike

我正在尝试从 rockyou 单词列表中读取内容并将所有 >= 8 个字符的单词写入新文件。

这是代码 -

def main():
with open("rockyou.txt", encoding="utf8") as in_file, open('rockout.txt', 'w') as out_file:
for line in in_file:
if len(line.rstrip()) < 8:
continue
print(line, file = out_file, end = '')
print("done")

if __name__ == '__main__':
main()

有些单词不是 utf-8。

Traceback (most recent call last):
File "wpa_rock.py", line 10, in <module>
main()
File "wpa_rock.py", line 6, in main
print(line, file = out_file, end = '')
File "C:\Python\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u0e45' in position
0: character maps to <undefined>

更新

def main():
with open("rockyou.txt", encoding="utf8") as in_file, open('rockout.txt', 'w', encoding="utf8") as out_file:
for line in in_file:
if len(line.rstrip()) < 8:
continue
out_file.write(line)
print("done")

if __name__ == '__main__':
main()```

Traceback (most recent call last):
File "wpa_rock.py", line 10, in <module>
main()
File "wpa_rock.py", line 3, in main
for line in in_file:
File "C:\Python\lib\codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1 in position 933: invali
d continuation byte

最佳答案

您的UnicodeEncodeError: 'charmap' 写入 out_file 期间发生错误(在 print() 中)。

默认情况下,open()使用locale.getpreferredencoding()这是 Windows 上的 ANSI 代码页(例如 cp1252 ),无法表示所有 Unicode 字符和 '\u0e45'性格特别。 cp1252是一个单字节编码,最多可以表示 256不同的字符,但有一百万 ( 1114111 ) Unicode 字符。它不能代表所有。

通过 encoding可以代表所有所需的数据,例如 encoding='utf-8'必须有效(如 @robyschek suggested )——如果您的代码为 utf-8如果数据没有任何错误,那么代码应该能够使用 utf-8 写入数据也。

<小时/>

您的UnicodeDecodeError: 'utf-8'读取时发生错误 in_file (for line in in_file)。并非所有字节序列都是有效的 utf-8,例如 os.urandom(100).decode('utf-8')可能会失败。做什么取决于应用程序。

如果您希望文件编码为utf-8;你可以通过errors="ignore" open()参数,以忽略偶尔无效的字节序列。或者您可以使用some other error handlers depending on your application .

如果文件中使用的实际字符编码不同,那么您应该传递实际的字符编码。 bytes本身没有任何编码 - 元数据应该来自另一个源(尽管 some encodings are more likely than others: chardet can guess ),例如,如果文件内容是 http 正文,则参见 A good way to get the charset/encoding of an HTTP response in Python

有时,损坏的软件可以生成大部分 utf-8 字节序列,其中一些字节采用不同的编码。 bs4.BeautifulSoup can handle some special cases 。您还可以try ftfy utility/library看看它是否对您的情况有帮助,例如 ftfy may fix some utf-8 variations .

关于python - 读取文件时出现 UnicodeEncodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37633927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com