Fra*_*ank 22 python unicode perl diacritics
我正在尝试学习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;
}
Run Code Online (Sandbox Code Playgroud)
该脚本只是将unicode元音变换为替代的ascii输出.(所以完整的输出是ascii.)我将不胜感激任何提示.谢谢!
Ian*_*ing 40
要转换为ASCII,您可能需要尝试ASCII,Dammit或此配方,其归结为:
>>> 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'
Run Code Online (Sandbox Code Playgroud)
小智 17
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),
Run Code Online (Sandbox Code Playgroud)
你可以像这样使用它:
$ 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
Run Code Online (Sandbox Code Playgroud)
如果您使用python 3字符串默认为unicode,并且如果它包含非ASCII字符甚至非拉丁字符,则不需要对其进行编码.所以解决方案将如下所示:
line = 'Verhältnismäßigkeit, Möglichkeit'
table = {
ord('ä'): 'ae',
ord('ö'): 'oe',
ord('ü'): 'ue',
ord('ß'): 'ss',
}
line.translate(table)
>>> 'Verhaeltnismaessigkeit, Moeglichkeit'
Run Code Online (Sandbox Code Playgroud)
您可以尝试unidecode
将Unicode转换为ascii,而不是编写手动正则表达式。它是Text::Unidecode
Perl模块的Python端口:
#!/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)
Run Code Online (Sandbox Code Playgroud)
它使用FileInput
类来避免全局状态。
例:
$ echo 'äöüß' | python toascii.py utf-8
aouss
Run Code Online (Sandbox Code Playgroud)