繁体   English   中英

如何修复或删除 Python3 中格式错误的 utf-8 字符

[英]How to fix or remove malformed utf-8 characters in Python3

我有几个文本文件,其中包含 python 3 无法处理的字符。 最麻烦的似乎是“关闭”引号。

我尝试使用以下方法阅读文件:

with open(filename, 'r', errors='backslashreplace') as file:
    text = file.read()
with open(filename, 'w', errors='backslashreplace') as file:
    file.write(text)

在 Notepad++ 中打开文件以查看字符时,我突出显示xE2 x80以指示非文本字符,然后是普通文本中的\\x9d

我看到涉及\\xE2\\x80\\x9D字符。 在 python REPL 中,我可以手动创建这样的字节对象,将其解码为 utf-8,并在打印时显示为我期望的字符。 我不确定为什么在读取文件时无法正确理解字符。

在读取文件以ignore错误而不是backslashreplace ,我仍然出现xE2 X80字符,而且我还没有弄清楚如何执行字符串操作来删除它们。

最终,我的目标是用普通引号替换所有这些奇怪的引号。 我可以想象有几种方法来实现这一点,但它们都需要我以某种方式解决(或删除) xE2 X80字符,或者正确读取 3 字节\\xE2\\x80\\x9D字符。

指定编码类型应该可以解决问题。 你可以这样做,

with open(filename, 'r', encoding='utf8', errors='backslashreplace' ) as file:
    text = file.read()
with open(filename, 'w', encoding='utf8', errors='backslashreplace') as file:
    file.write(text)

要创建省略错误字符的文件副本:

def sanitize_file(original_filename, sanitized_filename):
    with open(original_filename, 'r', encoding='utf8', errors='ignore') as original_file:
        with open(sanitized_filename, 'w', encoding='utf8') as sanitized_file:
            sanitized_file.write(original_file.read())

sanitize_file(filename, 'sanitized_' + filename)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM