Python 仅当前缀和后缀匹配时才使用 re.sub 替换字符串
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)
预期输出:
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 demo。
正则表达式看起来像
(?:Mein|ist|Wo|bist|du|is)(?=[,/!?()_0-9\-=+."\s\'])
见regex demo。详情:
(?:Mein|ist|Wo|bist|du|is)
- 备选字符串之一
(?=[,/!?()_0-9\-=+."\s\'])
- 匹配紧跟 ,
、/
、!
、?
、[=18= 的位置的正前瞻]、(
、_
、数字、-
、=
、+
、.
、"
、空格和 '
.
我正在尝试使用自定义词典将德语单词转换为英语。 在下面的代码中,仅当匹配词的后缀或前缀落在字符
中时才会发生替换[,\/!?()_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)
预期输出:
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 demo。
正则表达式看起来像
(?:Mein|ist|Wo|bist|du|is)(?=[,/!?()_0-9\-=+."\s\'])
见regex demo。详情:
(?:Mein|ist|Wo|bist|du|is)
- 备选字符串之一(?=[,/!?()_0-9\-=+."\s\'])
- 匹配紧跟,
、/
、!
、?
、[=18= 的位置的正前瞻]、(
、_
、数字、-
、=
、+
、.
、"
、空格和'
.