【问题标题】:Python replace a string using re.sub only if prefix and suffix matches仅当前缀和后缀匹配时,Python 才使用 re.sub 替换字符串
【发布时间】:2020-11-13 17:21:29
【问题描述】:

我正在尝试使用自定义词典将德语单词转换为英语。 在下面的代码中,仅当匹配单词的后缀或前缀落在字符中时才会发生替换

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

例如: Mein 应该首先转换,但不要在 MeinName 中转换,因为前缀和后缀不是上面提到的字符。如果有 _MeinMein. 这样的单个词,则需要进行转换。

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 

【问题讨论】:

  • 您的预期输出与您的规则不匹配:is234is 之后有一个2,因此,应将其替换为is。输出中_du 之前在哪里消失?
  • 现在,试试rx = r'(?:{})(?=[,/!?()_0-9\-=+."\s\'])'.format('|'.join(map(re.escape, replacements.keys())))
  • @wiktor 编辑了预期的输出。
  • 好的,ideone.com/3Rn0m1 对你有用吗?
  • 它的工作。谢谢@Wiktor Stribiżew

标签: python regex python-re


【解决方案1】:

你可以使用

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\']) - 与紧随其后的位置匹配的正向前瞻,/!?)(_、一个数字、-=+."、空格和'

【讨论】:

  • 感谢 Wiktor 的回答。我不知道前瞻/后视概念。在这里,我同时使用了积极的前瞻和后瞻,并且能够达到预期的结果。
猜你喜欢
  • 2021-06-25
  • 2011-10-05
  • 2022-06-10
  • 2023-01-30
  • 2014-06-26
  • 2019-10-26
  • 1970-01-01
  • 2012-08-11
  • 1970-01-01
相关资源
最近更新 更多