将字符串转换为带有特殊字符的unicode

时间:2014-03-14 05:59:57

标签: python

我有一个类似"Gregory RAST"的字符串,我想将其转换为"Grégory RAST"

我该怎么做?那个相反的过程是什么?

对于反向过程,我尝试使用decode方法,它适用于其中一些,有些则不适用

我不想使用ignore,因为它会转义某些字符并且显示的名称是错误的。

1 个答案:

答案 0 :(得分:0)

将文字从Grégory RAST转换为Gregory RAST

非常容易
>>> from unicodedata import normalize, combining
>>> aname = u'Grégory RAST'
>>> t1=unicodedata.normalize('NFD', aname)
>>> ''.join(c for c in t1 if not unicodedata.combining(c))
u'Gregory RAST'

如果不使用变音字符映射相同字符串之间的关系,并且没有它们,则无法向后转换:

>>> names = { u'Gregory RAST': u'Grégory RAST' }
>>> names[u'Gregory RAST']
u'Gr\xe9gory RAST'

否则,您怎么知道所需的字符串是Grégory RAST而不是Ģŕéğóŕŷ ŔĄŚŦ

相关问题