accented_string = u'Málaga'
# accented_string is of type 'unicode'
import unidecode
unaccented_string = unidecode.unidecode(accented_string)
# unaccented_string contains 'Malaga'and is of type 'str'
import unicodedata
def remove_accents(input_str):
nfkd_form = unicodedata.normalize('NFKD', input_str)
return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])
encoding = "utf-8" # or iso-8859-15, or cp1252, or whatever encoding you use
byte_string = b"café" # or simply "café" before python 3.
unicode_string = byte_string.decode(encoding)
Unidecode是这方面的正确答案。它将任何unicode字符串转换为ascii文本中最接近的表示形式
例如:
我刚刚在网上找到了这个答案:
它可以很好地工作(例如法语),但我认为第二步(删除重音)可能比删除非ASCII字符处理得更好,因为对于某些语言(例如希腊语),这将失败。最好的解决方案可能是显式删除标记为变音符号的unicode字符
编辑:这样做可以:
如果字符
unicodedata.combining(c)
可以与前面的字符组合,则c
将返回true,这主要是在它是变音符号的情况下编辑2:
remove_accents
需要的是unicode字符串,而不是字节字符串。如果有字节字符串,则必须将其解码为unicode字符串,如下所示:这个怎么样:
这也适用于希腊字母:
character category“Mn”代表
Nonspacing_Mark
,类似于MiniQuark答案中的unicodedata.combing(我没有想到unicodedata.combing,但它可能是更好的解决方案,因为它更明确)请记住,这些操作可能会显著改变文本的含义。口音、口音等不是“装饰”
相关问题 更多 >
编程相关推荐