2017-02-13 131 views
0

Python 3中有什么方法可以替代英文字母的一般语言特定字符吗?
例如,我有功能get_city(IP),返回与给定的IP连接的城市名称。它连接到外部数据库,所以我不能改变它的编码方式,我只是从数据库中获得价值。
我想这样做:用英文字母替换python中的语言特定字符

city = "České Budějovice" 
city = clear_name 
print(city) #should return "Ceske Budejoice" 

在这里,我用捷克语,但一般应该在任何非亚洲的langauge工作。

回答

2

尝试unidecode

# coding=utf-8 
from unidecode import unidecode 

city = "České Budějovice" 
print(unidecode(city.decode('utf-8'))) 

打印Ceske Budejovice根据需要(假设您的文章有一个错字)。

1

在这种情况下使用unicodedata模块。
为了获得所需的结果,你应该使用unicodedata.normalize()unicodedata.combining()功能正常化给定的字符串:

import unicodedata 

city = "České Budějovice" 
normalized = unicodedata.normalize('NFD', city) 
new_city = u"".join([c for c in normalized if not unicodedata.combining(c)]) 

print(new_city) # Ceske Budejovice 

NFD是四Unicode规范化形式之一

http://www.unicode.org/reports/tr15/