[英]Python replace a string using re.sub only if prefix and suffix matches
我正在尝试使用自定义词典将德语单词转换为英语。 在下面的代码中,仅当匹配词的后缀或前缀属于字符时才应进行替换
[,\/!?()_1234567890-=+."""' "]
例如: Mein
应该先转换, MeinName
中不需要转换,因为前缀和后缀不是上面提到的字符。 如果有像_Mein
或Mein.
它需要转换。
import re
str = "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()], str)
预计 output:
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\'])
请参阅正则表达式演示。 细节:
(?:Mein|ist|Wo|bist|du|is)
- 备选字符串之一(?=[,/?.()_0-9\-=+."\s\'])
- 与紧随其后的位置匹配的正前瞻,
, /
, !
, ?
, )
, (
, _
, 数字, -
, =
, +
, .
, "
, 空格和'
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.