是否有任何可以替换ASCII等效字符的lib,例如:
"Cze??"
Run Code Online (Sandbox Code Playgroud)
至:
"Czesc"
Run Code Online (Sandbox Code Playgroud)
我当然可以创建地图:
{'?':'s', '?': 'c'}
Run Code Online (Sandbox Code Playgroud)
并使用一些替换功能.但我不想将所有等价物硬编码到我的程序中,如果有一些功能已经这样做了.
nos*_*klo 33
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unicodedata
text = u'Cze??'
print unicodedata.normalize('NFD', text).encode('ascii', 'ignore')
Run Code Online (Sandbox Code Playgroud)
dan*_*n04 15
您可以通过以下方式完成大部分工作:
import unicodedata
def strip_accents(text):
return ''.join(c for c in unicodedata.normalize('NFKD', text) if unicodedata.category(c) != 'Mn')
Run Code Online (Sandbox Code Playgroud)
不幸的是,存在重音拉丁字母,不能分解为ASCII字母+组合标记.你必须手动处理它们.这些包括:
包unidecode最适合我:
from unidecode import unidecode
text = "Björn, ?ukasz and ????????."
print(unidecode(text))
# ==> Bjorn, Lukasz and Sokrates.
Run Code Online (Sandbox Code Playgroud)
您可能需要安装软件包:
pip install unidecode
Run Code Online (Sandbox Code Playgroud)
如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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13693 次 |
| 最近记录: |