在Python中将Unicode字符串近似转换为ASCII字符串
我不知道这是不是个简单的问题,但我需要把一个unicode字符串转换成ascii字符串,而且我不想看到那些转义字符。我是说,能不能把它转换成一些相似的ascii字符呢?
举个例子:Gavin O’Connor被转换成了Gavin O\x92Connor,但我希望它能直接变成Gavin O'Connor。这样做可能吗?有没有人写过工具来实现这个,还是说我得手动替换所有字符?
非常感谢!
Marco
5 个回答
9
b = str(a.encode('utf-8').decode('ascii', 'ignore'))
应该没问题。
13
import unicodedata
unicode_string = u"Gavin O’Connor"
print unicodedata.normalize('NFKD', unicode_string).encode('ascii','ignore')
输出:
Gavin O'Connor
这里有一份文件,里面描述了标准化形式:http://unicode.org/reports/tr15/
39
使用Unidecode这个工具包来转换字符串。
>>> import unidecode
>>> unidecode.unidecode(u'Gavin O’Connor')
"Gavin O'Connor"