我在Python中有一个Unicode字符串,我想删除所有的重音(变音符)。
我在网上找到了一个优雅的方法(在Java中):
将Unicode字符串转换为它的长规范化形式(使用单独的字符表示字母和变音符) 删除所有Unicode类型为“变音符”的字符。
我需要安装一个库,如pyICU或这是可能的Python标准库?那么python3呢?
重要提示:我希望避免使用从重音字符到非重音对应字符的显式映射的代码。
我在Python中有一个Unicode字符串,我想删除所有的重音(变音符)。
我在网上找到了一个优雅的方法(在Java中):
将Unicode字符串转换为它的长规范化形式(使用单独的字符表示字母和变音符) 删除所有Unicode类型为“变音符”的字符。
我需要安装一个库,如pyICU或这是可能的Python标准库?那么python3呢?
重要提示:我希望避免使用从重音字符到非重音对应字符的显式映射的代码。
当前回答
在我看来,所提出的解决办法不应该是公认的答案。原来的问题是要求去掉重音,所以正确的答案应该只去掉重音,而不是去掉重音加上其他未指明的变化。
简单地观察这段代码的结果,这是公认的答案。我把“Málaga”改成了“Málagueña”:
accented_string = u'Málagueña'
# accented_string is of type 'unicode'
import unidecode
unaccented_string = unidecode.unidecode(accented_string)
# unaccented_string contains 'Malaguena'and is of type 'str'
有一个额外的更改(ñ -> n),这在OQ中没有请求。
一个简单的函数,以较低的形式完成所请求的任务:
def f_remove_accents(old):
"""
Removes common accent characters, lower form.
Uses: regex.
"""
new = old.lower()
new = re.sub(r'[àáâãäå]', 'a', new)
new = re.sub(r'[èéêë]', 'e', new)
new = re.sub(r'[ìíîï]', 'i', new)
new = re.sub(r'[òóôõö]', 'o', new)
new = re.sub(r'[ùúûü]', 'u', new)
return new
其他回答
Gensim .utils.deaccent(text)来自Gensim -人类主题建模:
'Sef chomutovskych komunistu dostal postou bily prasek'
另一种解决方案是unicode。
请注意,建议的unicodedata解决方案通常只删除某些字符中的重音(例如,它将“ova”变成了“”,而不是“l”)。
这里已经有很多答案,但之前没有考虑过:使用sklearn
from sklearn.feature_extraction.text import strip_accents_ascii, strip_accents_unicode
accented_string = u'Málagueña®'
print(strip_accents_unicode(accented_string)) # output: Malaguena®
print(strip_accents_ascii(accented_string)) # output: Malaguena
如果您已经在使用sklearn处理文本,这一点特别有用。这些是由CountVectorizer等类内部调用的函数,用于规范化字符串:当使用strip_accent ='ascii'时,则调用strip_accents_ascii;当使用strip_accent ='unicode'时,则调用strip_accents_unicode。
更多的细节
最后,考虑文档字符串中的这些细节:
Signature: strip_accents_ascii(s)
Transform accentuated unicode symbols into ascii or nothing
Warning: this solution is only suited for languages that have a direct
transliteration to ASCII symbols.
and
Signature: strip_accents_unicode(s)
Transform accentuated unicode symbols into their simple counterpart
Warning: the python-level loop and join operations make this
implementation 20 times slower than the strip_accents_ascii basic
normalization.
我刚刚在网上找到了这个答案:
import unicodedata
def remove_accents(input_str):
nfkd_form = unicodedata.normalize('NFKD', input_str)
only_ascii = nfkd_form.encode('ASCII', 'ignore')
return only_ascii
它工作得很好(例如,对于法语),但我认为第二步(删除重音)可能比删除非ascii字符处理得更好,因为这对于某些语言(例如,希腊语)会失败。最好的解决方案可能是显式地删除标记为变音符的unicode字符。
编辑:这招管用:
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)])
如果字符c可以与前面的字符组合,主要是如果它是一个变音符,则unicodedata. combined (c)将返回true。
编辑2:remove_accent需要unicode字符串,而不是字节字符串。如果你有一个字节字符串,那么你必须像这样解码成一个unicode字符串:
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)
如果您希望获得类似Elasticsearch的ascii折叠过滤器的功能,您可能需要考虑fold-to-ascii,这是[本身]…
Apache Lucene ASCII折叠过滤器的Python端口,它将字母、数字和符号Unicode字符转换为不属于前127个ASCII字符的字符(“基本拉丁”Unicode块),如果它们存在的话。
下面是上面提到的一个例子:
from fold_to_ascii import fold
s = u'Astroturf® paté'
fold(s)
> u'Astroturf pate'
fold(s, u'?')
> u'Astroturf? pate'
编辑:fold_to_ascii模块似乎可以很好地规范化基于拉丁的字母;然而,不可映射的字符将被删除,这意味着该模块将减少中文文本,例如,空字符串。如果您想保留中文、日语和其他Unicode字母,可以考虑使用上面@mo-han的remove_accent_chars_regex实现。
有些语言将变音符组合成语言字母,并将重音变音符组合成重音。
我认为更安全的做法是明确指定你想要剥离的变量:
def strip_accents(string, accents=('COMBINING ACUTE ACCENT', 'COMBINING GRAVE ACCENT', 'COMBINING TILDE')):
accents = set(map(unicodedata.lookup, accents))
chars = [c for c in unicodedata.normalize('NFD', string) if c not in accents]
return unicodedata.normalize('NFC', ''.join(chars))