python - 将非ascii字符转换为特定字符

时间:2014-06-24 16:40:57

标签: python decode iso-8859-1 non-ascii-characters


大家好,感谢您的时间!

我有iso-8859-1 html文件作为输入,用html实体代替非ascii字符,这很整洁。除了只有一个字符: - (00C9 unicode代码点,以防它不显示)。我想将它转换为“oe”以摆脱它。

我已经尝试过了     iconv -f iso-8859-1 -t ascii // translit

但它会消除有问题的角色并且不会放置任何东西。

我使用python 2.7,我尝试了解码,编码,编解码器的几个方面,但我不会去任何地方。 这是我的代码:

i=0
for file in os.listdir(dir_in):
i+=1
file=codecs.open(dir_in+file,"r","iso-8859-1")
out=codecs.open(dir_out+str(i)+".html","w","utf-8")
    for line in file:
            #at this point the type of line is "unicode"
    line=line.decode("iso-8859-1",errors="replace")
            out.write(line)
file.close
out.close

(我无法正确显示缩进显示,但我保证这部分没问题) 我得到一个“ascii编解码器无法编码字符u \ x9c”错误。我不确定我是否正在使用解码。

我也尝试过:

line=unicode(line)

在没有替换的情况下摆脱了角色(这就是它应该做的事情)

line=unicode(line, errors="replace")

这给了我“TypeError:不支持解码Unicode” 我想这两个没有用,因为我不应该给“unicode”一个已经unicode的东西。

如果你有一个简单的方法在bash或perl中做到这一点我也很感兴趣,但我不能使用python 3,因为服务器不支持运行该东西。

非常感谢!

1 个答案:

答案 0 :(得分:0)

在尝试编写该字符之前,你能问replace这个字符吗?:

line = line.replace(u"\x9c", "oe")