【发布时间】:2013-11-04 16:00:10
【问题描述】:
我正在尝试从文本文档中删除所有非 ascii 字符。我找到了一个可以做到这一点的包,https://pypi.python.org/pypi/Unidecode
它应该接受一个字符串并将所有非 ascii 字符转换为最接近的可用 ascii 字符。我通过调用while (<input>) { $_ = unidecode($_); } 在 perl 中轻松使用了相同的模块,这是 perl 模块的直接端口,文档表明它应该可以正常工作。
我确定这很简单,我只是对字符和文件编码了解不够,无法知道问题所在。我的 origfile 以 UTF-8 编码(从 UCS-2LE 转换而来)。这个问题可能更多地与我缺乏编码知识和处理错误的字符串有关,而不是模块,希望有人能解释原因。我已经尝试了我所知道的一切,而不仅仅是随机插入代码并搜索我到目前为止没有运气的错误。
这是我的蟒蛇
from unidecode import unidecode
def toascii():
origfile = open(r'C:\log.convert', 'rb')
convertfile = open(r'C:\log.toascii', 'wb')
for line in origfile:
line = unidecode(line)
convertfile.write(line)
origfile.close()
convertfile.close()
toascii();
如果我没有以字节模式 (origfile = open('file.txt','r') 打开原始文件,那么我会从 for line in origfile: 行收到错误 UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 1563: character maps to <undefined>。
如果我以字节模式打开它'rb',我会从line = unidecode(line) 行得到TypeError: ord() expected string length 1, but int found。
如果我将 line 声明为字符串line = unidecode(str(line)),那么它将写入文件,但是......不正确。 \r\n'b'\xef\xbb\xbf[ 2013.10.05 16:18:01 ] User_Name > .\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\ 它正在写出 \n、\r 等和 unicode 字符,而不是将它们转换成任何东西。
如果我如上所述将行转换为字符串,并以字节模式打开转换文件'wb',则会出现错误TypeError: 'str' does not support the buffer interface
如果我以字节模式打开它而不将其声明为字符串 'wb' 和 unidecode(line),那么我会再次收到 TypeError: ord() expected string length 1, but int found 错误。
【问题讨论】: