python - 将不同的编码转换为ascii

标签 python encoding character-encoding

我有一百个文件,根据 chardet,每个文件都使用以下编码之一:

['UTF-8', 'ascii', 'ISO-8859-2', 'UTF-16LE', 'TIS-620', 'utf-8', 'SHIFT_JIS', 'ISO-8859-7']

所以我知道文件编码,因此我知道用什么编码打开文件。

我希望将所有文件仅转换为 ascii。我还希望将不同版本的字符(如 -')转换为它们的普通 ascii 等效字符。例如b"\xe2\x80\x94".decode("utf8")应该转换成-。最重要的是文本易于阅读。例如,我不想 don t,而是 don't

我该怎么做?

我可以使用 Python 2 或 3 来解决这个问题。

这是我对 Python2 的了解。我正在尝试检测那些以连续非 ascii 字符开头的行。

for file_name in os.listdir('.'):
        print(file_name)
        r = chardet.detect(open(file_name).read())
        charenc = r['encoding']
        with open(file_name,"r" ) as f:
            for line in f.readlines():
              if line.decode(charenc) != line.decode("ascii","ignore"):
                print(line.decode("ascii","ignore"))

这给了我以下异常:

    if line.decode(charenc) != line.decode("ascii","ignore"):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_16_le.py", line 16, in decode
    return codecs.utf_16_le_decode(input, errors, True)
UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 6: truncated data

最佳答案

不要将 .readlines() 用于包含多字节行的二进制文件。在 UTF-16 little-endian 中,换行符被编码为两个字节,0A(在 ASCII 中为换行符)和 00(NULL)。 .readlines() 在这两个字节的第一个 处拆分,留下不完整的数据进行解码。

使用io 库重新打开文件以便于解码:

import io

for file_name in os.listdir('.'):
    print(file_name)
    r = chardet.detect(open(file_name).read())
    charenc = r['encoding']
    with io.open(file_name, "r", encoding=charenc) as f:
        for line in f:
            line = line.encode("ascii", "ignore"):
            print line

要用 ASCII 友好字符替换特定的 unicode 代码点,请使用字典映射代码点到代码点或 unicode 字符串并调用 line.translate()第一:

charmap = {
    0x2014: u'-',   # em dash
    0x201D: u'"',   # comma quotation mark, double
    # etc.
}

line = line.translate(charmap)

我使用十六进制整数文字来定义 unicode 代码点以映射到这里。字典中的值必须是 unicode 字符串、整数(代码点)或 None 以完全删除该代码点。

关于python - 将不同的编码转换为ascii,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19644507/

相关文章:

java - 使用来自 CSV 的 Java+mySQL 插入特定字符集

python - 如何在 Tkinter 中更改图像的分辨率?

command-line - 在批处理文件的输入文件中使用 "En Dash"

php - 如何获得有关用于发送表单数据的编码的提示(在 PHP 中)

powershell - 将文件转换为 UTF-8 : Get-Content : Exception of type 'System.OutOfMemoryException' was thrown

java - 编码问题

python - 没有模块名册

python - Pandas 相当于 dplyr dot

python - MySQL INSERT ... ON DUPLICATE KEY UPDATE with django 1.4 for bulk insert

python - utf-8编码的html文件中包含非utf-8字符怎么办?