用ASCII替换特殊字符
有没有什么库可以把特殊字符替换成ASCII字符,比如:
"Cześć"
变成:
"Czesc"
当然,我可以自己创建一个映射表:
{'ś':'s', 'ć': 'c'}
然后用一些替换的函数。但是我不想把所有的对应关系都写死在我的程序里,如果有现成的函数可以做到这一点就好了。
6 个回答
23
你可以通过以下方式完成大部分工作:
import unicodedata
def strip_accents(text):
return ''.join(c for c in unicodedata.normalize('NFKD', text) if unicodedata.category(c) != 'Mn')
不过,有一些带重音的拉丁字母是无法拆分成一个ASCII字母加上组合符号的。你需要手动处理这些字母。它们包括:
- Æ → AE
- Ð → D
- Ø → O
- Þ → TH
- ß → ss
- æ → ae
- ð → d
- ø → o
- þ → th
- Œ → OE
- œ → oe
- ƒ → f
24
我觉得这个叫做 unidecode 的包效果最好:
from unidecode import unidecode
text = "Björn, Łukasz and Σωκράτης."
print(unidecode(text))
# ==> Bjorn, Lukasz and Sokrates.
你可能需要先安装这个包:
pip install unidecode
上面这个方法比其他答案提到的用 unicodedata.normalize()
来编码(和解码)输出要简单而且更可靠。
# This doesn't work as expected:
ret = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore')
print(ret)
# ==> b'Bjorn, ukasz and .'
# Besides not supporting all characters, the returned value is a
# bytes object in python3. To yield a str type:
ret = ret.decode("utf8") # (not required in python2)
50
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unicodedata
text = u'Cześć'
print unicodedata.normalize('NFD', text).encode('ascii', 'ignore')
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。