gpt4 book ai didi

python - 修复损坏的编码(使用 Python)

转载 作者:太空宇宙 更新时间:2023-11-04 09:06:05 29 4
gpt4 key购买 nike

我有一堆文本文件包含编码错误的韩文字符。具体来说,字符似乎是用 EUC-KR 编码的,但文件本身是用 UTF8+BOM 保存的。

到目前为止,我设法用以下内容修复了一个文件:

  1. 用EditPlus打开文件(显示文件编码为UTF8+BOM)
  2. 在 EditPlus 中,将文件另存为 ANSI
  3. 最后,在 Python 中:

    with codecs.open(html, 'rb', encoding='euc-kr') as source_file:
    contents = source_file.read()

    with open(html, 'w+b') as dest_file:
    dest_file.write(contents.encode('utf-8'))

我想把它自动化,但我没能做到。我可以用 Python 打开原始文件:

codecs.open(html, 'rb', encoding='utf-8-sig')

但是,我一直无法弄清楚如何执行 2. 部分。

最佳答案

我在这里假设您的文本已经编码为 EUC-KR,然后再次编码为 UTF-8。如果是这样,编码为 Latin 1(Windows 称之为 ANSI)确实是返回原始 EUC-KR 字节串的最佳方式。

以带 BOM 的 UTF8 格式打开文件,编码为 Latin1,解码为 EUC-KR:

import io

with io.open(html, encoding='utf-8-sig') as infh:
data = infh.read().encode('latin1').decode('euc-kr')

with io.open(html, 'w', encoding='utf8') as outfh:
outfh.write(data)

我正在使用 io.open() function这里代替 codecs 作为更健壮的方法; io 是新的 Python 3 库,也向后移植到 Python 2。

演示:

>>> broken = '\xef\xbb\xbf\xc2\xb9\xc3\x8c\xc2\xbc\xc3\xba'
>>> print broken.decode('utf-8-sig').encode('latin1').decode('euc-kr')
미술

关于python - 修复损坏的编码(使用 Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20768475/

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