将不同的编码转换为ascii

Baz*_*Baz 2 python encoding character-encoding

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

['UTF-8', 'ascii', 'ISO-8859-2', 'UTF-16LE', 'TIS-620', 'utf-8', 'SHIFT_JIS', 'ISO-8859-7']
Run Code Online (Sandbox Code Playgroud)

所以我知道文件编码,因此我知道打开文件的编码方式.

我希望只将所有文件转换为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"))
Run Code Online (Sandbox Code Playgroud)

这给了我以下例外:

    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
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

不要使用.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
Run Code Online (Sandbox Code Playgroud)

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

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

line = line.translate(charmap)
Run Code Online (Sandbox Code Playgroud)

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