如何用 Python 中的 ascii 字符替换 unicode 字符(给出的 perl 脚本)?
问题描述:
我正在尝试学习 python,但不知道如何将以下 perl 脚本转换为 python:
I am trying to learn python and couldn't figure out how to translate the following perl script to 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 umlauts 更改为替代的 ascii 输出.(所以完整的输出是 ascii.)我将不胜感激任何提示.谢谢!
The script just changes unicode umlauts to alternative ascii output. (So the complete output is in ascii.) I would be grateful for any hints. Thanks!
答
#!/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 字符甚至非拉丁字符,则不需要对其进行编码.所以解决方案如下:
In case you are using python 3 strings are by default unicode and you dont' need to encode it if it contains non-ASCII characters or even a non-Latin characters. So the solution will look as follow:
line = 'Verhältnismäßigkeit, Möglichkeit'
table = {
ord('ä'): 'ae',
ord('ö'): 'oe',
ord('ü'): 'ue',
ord('ß'): 'ss',
}
line.translate(table)
>>> 'Verhaeltnismaessigkeit, Moeglichkeit'