如何用Python中的ascii字符替换unicode字符(给出perl脚本)?

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)

  • 是的,但它实际上正是我现在所需要的! (3认同)
  • große - > groe?!? (3认同)
  • 这根本不是什么原始.pl所做的(主要是恰当地音译德国特殊字符) (2认同)

小智 17

  • 使用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), 
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)

  • 目标似乎是解除德语文本,使其易于理解.在这段代码中`ord(u'ß'):None`的效果是**删除**ß("eszett")字符.它应该是'ord(u'ß'):你's'.Upvotes?接受的答案??? (5认同)
  • 哦.来.上.我试图展示地图的不同可能性. (5认同)

jfs*_*jfs 5

您可以尝试unidecode将Unicode转换为ascii,而不是编写手动正则表达式。它是Text::UnidecodePerl模块的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)