![](/img/trans.png)
[英]Python 2.7 regex statement with multiple option acute and grave accents
[英]Python 2.7 regex statement to add acute accent to the first matching character
我正在嘗試使用Python正則表達式為兩個字符模式的第一個匹配字符添加尖銳的重音符號。 例如,我希望oä́
成為óä́
。 下面是我正在使用的正則表達式代碼。
raw = oä́gtra’
raw = re.sub(ur"([ieäaouëö])([í|é|ä́|á|ó|ú|ö́|ë́])", ur"\1́\2", raw) # notice the acute accent between \1 and \2
為了幫助解決此問題,我使用以下語句。
if re.match(ur"([ieäaouëö])([í|é|ä́|á|ó|ú|ö́|ë́])", raw) is not None:
print "it found the pattern..."
語句'it found the pattern ...'被打印出來,因此看來我的regex語句正確地識別了該模式,我只需要幫助就可以將尖銳的重音添加到第一個匹配字符上。
以下是我也嘗試過的其他代碼。 但是這段代碼似乎也不起作用。
print repr(raw) # prints u'o\xe4\u0301gtra\u2019'
mapping = {"i":"í","e":"é","ä":"ä́","a":"á","o":"ó","u":"ú","ö":"ö́","ë":"ë́"}
pattern = "([ieäaouëö])([í|é|ä́|á|ó|ú|ö́|ë́])"
replacement = lambda match: mapping[match.group(1)] + match.group(2)
raw = re.sub(pattern, replacement, raw)
感謝您提供的所有答復以及以后的任何幫助! 非常感謝!
您可以嘗試使用ord
和chr
以及編碼來做一些魔術,但是我認為最好不要對映射進行硬編碼。
mapping = {"i":"í","e":"é","ä":"ä","a":"á","o":"ó","u":"ú","ö":"ö","ë":"ë"}
pattern = "([aeiou])([aeiou])"
replacement = lambda match: mapping[match.group(1)] + match.group(2)
text = re.sub(pattern, replacement, text)
請注意,它是不完整的,您需要擴展字典和正則表達式模式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.