Python 2.7正则表达式语句为第一个匹配的字符添加急性重音

时间:2014-05-25 19:26:01

标签: python regex python-2.7

我试图使用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..."

声明'它找到了模式......'打印所以看起来我的正则表达式声明正确识别我需要帮助将模式添加到第一个匹配字符的模式。

以下是我也尝试过的其他代码。但是这段代码似乎也没有用。

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)

感谢所有提供的答案和未来的任何帮助!非常感谢!

1 个答案:

答案 0 :(得分:0)

您可以尝试使用ordchr以及编码做一些魔术,但我认为您最好使用硬编码映射。

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)

请注意,它不完整,您需要扩展字典和正则表达式