不知道这是否微不足道,但我需要将Unicode字符串转换为ASCII字符串,并且我不想在周围有所有这些转义字符。我的意思是,是否可能将其“近似”转换为一些相当类似的ASCII字符?
例如:Gavin O’Connor被转换为Gavin O\x92Connor,但我真的希望它只被转换为Gavin O'Connor。这可能吗?是否有人编写了一些实用程序来执行此操作,还是我必须手动替换所有字符?
非常感谢! 马尔科
不知道这是否微不足道,但我需要将Unicode字符串转换为ASCII字符串,并且我不想在周围有所有这些转义字符。我的意思是,是否可能将其“近似”转换为一些相当类似的ASCII字符?
例如:Gavin O’Connor被转换为Gavin O\x92Connor,但我真的希望它只被转换为Gavin O'Connor。这可能吗?是否有人编写了一些实用程序来执行此操作,还是我必须手动替换所有字符?
非常感谢! 马尔科
使用Unidecode包来对字符串进行音译。
>>> import unidecode
>>> unidecode.unidecode(u'Gavin O’Connor')
"Gavin O'Connor"
- Marco Moschettini导入unidecode unidecode.unidecode(u'Gavin O’Connor') "Gavin OConnor"
'
是一个Unicode字符,没有ASCII等效项。至少在Python中,'
不是’
。您可能希望创建一个特殊字符的字典,并存储类似外观的ASCII字符。然后,您可以将Unicode字符替换为相应的ASCII字符。 - D Kimport unicodedata
unicode_string = u"Gavin O’Connor"
print unicodedata.normalize('NFKD', unicode_string).encode('ascii','ignore')
输出:
Gavin O'Connor
这里有一个描述规范化形式的文档: http://unicode.org/reports/tr15/
unicodedata.normalize('NFKD', u'Gavin O\u2019Connor') == u'Gavin O\u2019Connor'
,以及u'Gavin O\u2019Connor'.encode('ascii', 'ignore') == 'Gavin OConnor'
。我对你链接的标准感到非常困惑,所以我无法确定这是unicodedata.normalize
的错误还是正确行为。 - slowdogunicodedata.normalize('NFKD',u"Gavin O'Connor"). encode('ascii', 'ignore')
会给我返回 "Gavin O'Connor"
。 - Acornb = str(a.encode('utf-8').decode('ascii', 'ignore'))
尝试简单的字符替换
str1 = "“I am the greatest”, said Gavin O’Connor"
print(str1)
print(str1.replace("’", "'").replace("“","\"").replace("”","\""))
附注:如果您遇到error的情况,请在您的.py
文件顶部添加# -*- coding: utf-8 -*-