[英]Regex for accent insensitive replacement in python
在Python 3中,我希望能夠以“不區分重音”的方式使用re.sub()
,因為我們可以使用re.I
標志來進行不區分大小寫的替換。
可能像re.IGNOREACCENTS
標志:
original_text = "¿It's 80°C, I'm drinking a café in a cafe with Chloë。"
accent_regex = r'a café'
re.sub(accent_regex, 'X', original_text, flags=re.IGNOREACCENTS)
這將導致“¿它的溫度為80°C,我正在用Chloë在X中飲用X.”(請注意,“Chloë”仍然有一個重點而不是“¿它是80°C,我正在飲用X”與Chloë的咖啡館。“在真正的蟒蛇。
我認為這樣的旗幟不存在。 那么這樣做的最佳選擇是什么? 使用re.finditer
和unidecode
兩個original_text
和accent_regex
然后通過分割字符串替換? 或者通過重音變體修改accent_regex
的所有字符,例如: r'[cç][aàâ]f[éèêë]'
?
通常會提到unidecode
來刪除Python中的重音符號,但它也不止unidecode
:它將'°'
轉換為'deg'
,這可能不是所需的輸出。
此方法應適用於任何模式和任何文本。
您可以暫時從文本和正則表達式模式中刪除重音。 來自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+
查找文本中的每個單詞 X
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ë.
您可以使用Unidecode :
$ pip install unidecode
在你的程序中:
from unidecode import unidecode
original_text = "I'm drinking a café in a cafe."
unidecoded_text = unidecode(original_text)
regex = r'cafe'
re.sub(regex, 'X', unidecoded_text)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.