首页 > 解决方案 > Python 产生 kysl� 而不是 kyslá

问题描述

标签: python-3.xcorruption

解决方案


首先,您不需要对字符串进行任何编码和解码。

切勿在未明确指定文件编码的情况下打开文本文件。这是一个简单而普遍的规则。如果不知道正在读取(或写入)的文件的编码,并让 Python 使用它感觉使用的任何默认值,那么所有的赌注都将失败。

HTML 文件往往采用 UTF-8 编码。另一个可能的候选者是 Windows-1252 ( cp1252)。但实际上这取决于文件是如何创建的,因此您必须检查。

这应该非常接近您的想法。此代码的任何部分都不涉及对任何字符串进行编码 -open()为您执行此操作。

with open("org22.htm", "r", encoding="utf8") as infile:
    html = infile.read()

start = "I = new Array();"
end = "State = new Array();"
pos1 = html.find(start) + len(start)
pos2 = html.rfind(end)

lines = html[pos1:pos2].splitlines()

with open("dump.txt", "w", encoding="utf8") as outfile:
    for i, line in enumerate(lines):
        if f"I[{i}][1][0][0] =" in line:
            data = line.split("'")[-2]
            outfile.write(data + "\n")

推荐阅读