unidecode
经常提到在 Python 中删除重音符号,但它的作用还不止于此:它转换'°'
为'deg'
,这可能不是所需的输出。
unicodedata
似乎有足够的功能来删除口音。
任何图案
此方法适用于任何模式和任何文本。
您可以暂时从文本和正则表达式模式中删除重音符号。来自re.finditer()
(开始和结束索引)的匹配信息可用于修改原始的重音文本。
请注意,必须颠倒匹配项,以免修改以下索引。
import re
import unicodedata
original_text = "I'm drinking a 80° café in a cafe with Chloë, François Déporte and Francois Deporte."
accented_pattern = r'a café|François Déporte'
def remove_accents(s):
return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn'))
print(remove_accents('äöüßéèiìììíàáç'))
# aoußeeiiiiiaac
pattern = re.compile(remove_accents(accented_pattern))
modified_text = original_text
matches = list(re.finditer(pattern, remove_accents(original_text)))
for match in matches[::-1]:
modified_text = modified_text[:match.start()] + 'X' + modified_text[match.end():]
print(modified_text)
# I'm drinking a 80° café in X with Chloë, X and X.
如果模式是一个词或一组词
你可以 :
- 从你的模式词中删除重音并将它们保存在一个集合中以便快速查找
- 查找文本中的每个单词
\w+
- 从单词中删除重音:
import re
from unidecode import unidecode
original_text = "I'm drinking a café in a cafe with Chloë."
def remove_accents(string):
return unidecode(string)
accented_words = ['café', 'français']
words_to_remove = set(remove_accents(word) for word in accented_words)
def remove_words(matchobj):
word = matchobj.group(0)
if remove_accents(word) in words_to_remove:
return 'X'
else:
return word
print(re.sub('\w+', remove_words, original_text))
# I'm drinking a X in a X with Chloë.