【问题标题】:broken CJK data when reading ISO-8859-1 file in python在 python 中读取 ISO-8859-1 文件时损坏的 CJK 数据
【发布时间】:2020-12-16 23:07:27
【问题描述】:

我正在解析一些 ISO-8859-1 的文件,其中包含中文、日文、韩文字符。

import os
from os import listdir

cnt = 0
base_path = 'data/'
cwd = os.path.abspath(os.getcwd())
for f in os.listdir(base_path):
    path = cwd + '/' + base_path + f
    cnt = 0
    with open(path, 'r', encoding='ISO-8859-1') as file:
        for line in file:
            print('line {}: {}'.format(cnt, line))
            cnt +=1 

代码运行,但打印出损坏的字符。其他 stackoverflow 问题建议我使用编码和解码。例如,对于韩语文本,我尝试过 file.read().encode('latin1').decode('euc-kr'),但这并没有做任何事情。我还尝试使用iconv 将文件转换为utf-8,但转换后的文本文件中的字符仍然损坏。

任何建议将不胜感激。

【问题讨论】:

    标签: python utf-8 iso-8859-1


    【解决方案1】:

    对不起,没有。 ISO-8859-1 中不能有任何中文、日文或韩文字符。代码页一开始就不支持它们。

    您在代码中所做的是让 Python 假定文件采用 ISO-8859-1 编码并返回字符Unicode(这是构建字符串的方式)。如果在open() 中没有指定encoding 参数,默认会假设UTF-8 编码使用在文件中 并且仍然返回in Unicode,即逻辑未指定任何编码的字符。

    现在的问题是这些 CJK 字符是如何在文件中编码的。如果您知道答案,您只需将正确的编码参数放入open() 即可立即生效。假设它是你提到的 EUC-KR,代码应该是:

    with open(path, 'r', encoding='euc-kr') as file:
        for line in file:
            print('line {}: {}'.format(cnt, line))
            cnt +=1 
    

    如果您感到沮丧,请查看chardet。它应该可以帮助您从文本中检测编码。示例:

    import chardet
    with open(path, 'rb') as file:
        rawdata = file.read()
        guess = chardet.detect(rawdata) # e.g. {'encoding': 'EUC-KR', 'confidence': 0.99}
        text = guess.decode(guess['encoding'])
        cnt = 0
        for line in text.splitlines():
            print('line {}: {}'.format(cnt, line))
            cnt +=1 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 2012-07-26
      • 1970-01-01
      相关资源
      最近更新 更多