如何在Python中用ASCII字符替换Unicode字符(给出Perl脚本)?
我正在学习Python,但不知道怎么把下面的Perl脚本转换成Python:
#!/usr/bin/perl -w
use open qw(:std :utf8);
while(<>) {
s/\x{00E4}/ae/;
s/\x{00F6}/oe/;
s/\x{00FC}/ue/;
print;
}
这个脚本的作用是把Unicode中的变音符号(比如德语的ü、ö等)转换成其他的ASCII字符(就是常见的字母)。所以最后的输出都是ASCII格式的。如果有人能给我一些建议,我会非常感激。谢谢!
5 个回答
7
你可以试试 unidecode
这个工具,它可以把Unicode字符转换成ascii字符,这样就不用自己写复杂的正则表达式了。这个工具是Python版本的 Text::Unidecode
Perl模块。
#!/usr/bin/env python
import fileinput
import locale
from contextlib import closing
from unidecode import unidecode # $ pip install unidecode
def toascii(files=None, encoding=None, bufsize=-1):
if encoding is None:
encoding = locale.getpreferredencoding(False)
with closing(fileinput.FileInput(files=files, bufsize=bufsize)) as file:
for line in file:
print unidecode(line.decode(encoding)),
if __name__ == "__main__":
import sys
toascii(encoding=sys.argv.pop(1) if len(sys.argv) > 1 else None)
它使用了 FileInput
类来避免全局状态的问题。
举个例子:
$ echo 'äöüß' | python toascii.py utf-8
aouss
48
如果你想把内容转换成ASCII格式,可以试试这个网站 ASCII, Dammit 或者这个方法 this recipe,其实就是:
>>> title = u"Klüft skräms inför på fédéral électoral große"
>>> import unicodedata
>>> unicodedata.normalize('NFKD', title).encode('ascii','ignore')
'Kluft skrams infor pa federal electoral groe'
18
- 使用
fileinput
模块来循环读取标准输入或者一系列文件, - 把你从文件中读取的每一行从UTF-8格式解码成unicode对象,
- 然后用
translate
方法来转换你想要的unicode字符。
translit.py
的代码大概是这样的:
#!/usr/bin/env python2.6
# -*- coding: utf-8 -*-
import fileinput
table = {
0xe4: u'ae',
ord(u'ö'): u'oe',
ord(u'ü'): u'ue',
ord(u'ß'): None,
}
for line in fileinput.input():
s = line.decode('utf8')
print s.translate(table),
你可以这样使用它:
$ cat utf8.txt
sömé täßt
sömé täßt
sömé täßt
$ ./translit.py utf8.txt
soemé taet
soemé taet
soemé taet
- 更新:
如果你使用的是Python 3,字符串默认就是unicode格式,所以如果字符串里有非ASCII字符或者非拉丁字符,你就不需要再进行编码了。这样的话,解决方案看起来会是:
line = 'Verhältnismäßigkeit, Möglichkeit'
table = {
ord('ä'): 'ae',
ord('ö'): 'oe',
ord('ü'): 'ue',
ord('ß'): 'ss',
}
line.translate(table)
>>> 'Verhaeltnismaessigkeit, Moeglichkeit'