Python的"这个Unicode的最佳ASCII"数据库在哪里?

joe*_*ker 84 python unicode ascii

我有一些使用Unicode标点符号的文本,如左双引号,右引号为撇号,等等,我需要用ASCII格式.Python是否有一个具有明显ASCII替代品的这些字符的数据库,所以我可以把它们全部变成"?".?

joe*_*ker 87

Unidecode看起来像一个完整的解决方案.它将花哨的引号转换为ascii引号,将重音拉丁字符转换为无重音,甚至尝试音译来处理不具有ASCII等效字符的字符.这样你的用户不必看到一堆?当你必须通过传统的7位ascii系统传递他们的文本时.

>>> from unidecode import unidecode
>>> print unidecode(u"\u5317\u4EB0")
Bei Jing 
Run Code Online (Sandbox Code Playgroud)

http://www.tablix.org/~avian/blog/archives/2009/01/unicode_transliteration_in_python/

  • @ThiefMaster是否适用于所有语言?也许Unidecode是最低的共同点. (4认同)
  • 事实上,例如在芬兰语中,虽然`ä - > a`,`ö - > o`是完全错误的,但它仍然优于`ae`和`oe` (4认同)
  • 嗯..德语变音符号被转换为它们的基本字符而不是例如ö= oe,ä= ae等. (3认同)

Mik*_*oss 24

在我原来的答案中,我也提出了建议unicodedata.normalize.但是,我决定测试它,结果证明它不适用于Unicode引号.它在翻译带重音的Unicode字符方面做得很好,所以我猜unicodedata.normalize是使用该unicode.decomposition函数实现的,这让我相信它可能只能处理字母和变音符号组合的Unicode字符,但我不是真的关于Unicode规范的专家,所以我可以充满热气......

无论如何,您可以使用unicode.translate来处理标点字符.该translate方法将Unicode序数字典转换为Unicode序数,因此您可以创建一个映射,将仅Unicode标点符号转换为ASCII兼容标点符号:

'Maps left and right single and double quotation marks'
'into ASCII single and double quotation marks'
>>> punctuation = { 0x2018:0x27, 0x2019:0x27, 0x201C:0x22, 0x201D:0x22 }
>>> teststring = u'\u201Chello, world!\u201D'
>>> teststring.translate(punctuation).encode('ascii', 'ignore')
'"hello, world!"'
Run Code Online (Sandbox Code Playgroud)

如果需要,您可以添加更多标点符号映射,但我认为您不必担心处理每个Unicode标点字符.如果您确实需要处理重音和其他变音符号,您仍然可以使用它unicodedata.normalize来处理这些字符.


eas*_*sel 21

有趣的问题.

谷歌帮助我找到了这个使用unicodedata模块的页面,如下所示:

import unicodedata
unicodedata.normalize('NFKD', title).encode('ascii','ignore')
Run Code Online (Sandbox Code Playgroud)