仅当前缀和后缀匹配时,才使用re.sub替换字符串



我正在尝试使用自定义词典将德语单词转换为英语。在下面的代码中,只有当匹配单词的后缀或前缀位于字符中时,才应该进行替换

[,/!?()_1234567890-=+."""' "]

例如:

首先应转换Mein,但不应在MeinName中转换,因为前缀和后缀不是上述字符。如果存在像_MeinMein.这样的单个单词,则需要对它们进行转换。

import re
string = "Mein ,Name, ist John, Wo23 bist+ ,_du? , MeinName "
replacements = {
'Mein': 'my',
'ist': 'is',
'Wo': 'where',
'bist': 'are',
'du': 'you',
'is': 'iis'
}
re.sub(
'({})'.format('|'.join(map(re.escape, replacements.keys()))),
lambda m: replacements[m.group()],
string
)

预期输出:

my ,name,is John,where23 are+,_you? ,MeinName 

您可以使用

import re
s = "Mein ,Name, ist John, Wo23 bist+ ,_du? , MeinName "
replacements = { "Mein": "my", "ist": "is", "Wo":"where", "bist":"are", "du":"you", "is" :"iis"}
rx = r'(?:{})(?=[,/!?()_0-9-=+."s'])'.format('|'.join(map(re.escape, replacements.keys())))
print (rx)
print ( re.sub(rx, lambda m: replacements[m.group()], s) )
# => my ,Name, is John, where23 are+ ,_you? , MeinName 

请参阅Python演示。

正则表达式看起来像

(?:Mein|ist|Wo|bist|du|is)(?=[,/!?()_0-9-=+."s'])

请参阅regex演示。详细信息:

  • (?:Mein|ist|Wo|bist|du|is)-备用字符串之一
  • (?=[,/!?()_0-9-=+."s'])-与紧接着,/!?)(_、数字、-=+."、空白和'的位置匹配的正向前瞻

最新更新