繁体   English   中英

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

[英]How to replace unicode characters by ascii characters in Python (perl script given)?

我正在尝试学习 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 umlauts 更改为替代的 ascii 输出。 (所以完整的输出是 ascii。)我将不胜感激任何提示。 谢谢!

要转换为 ASCII,您可能想尝试ASCII、Dammit这个 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'
  • 使用fileinput模块循环标准输入或文件列表,
  • 将您从 UTF-8 读取的行解码为 un​​icode 对象
  • 然后使用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'

您可以尝试使用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)

它使用FileInput类来避免全局状态。

例子:

$ echo 'äöüß' | python toascii.py utf-8
aouss

我使用translitcodec

>>> import translitcodec
>>> print '\xe4'.decode('latin-1')
ä
>>> print '\xe4'.decode('latin-1').encode('translit/long').encode('ascii')
ae
>>> print '\xe4'.decode('latin-1').encode('translit/short').encode('ascii')
a

您可以将解码语言更改为您需要的任何语言。 您可能需要一个简单的函数来减少单个实现的长度。

def fancy2ascii(s):
    return s.decode('latin-1').encode('translit/long').encode('ascii')

又快又脏(python2):

def make_ascii(string):
    return string.decode('utf-8').replace(u'ü','ue').replace(u'ö','oe').replace(u'ä','ae').replace(u'ß','ss').encode('ascii','ignore');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM