【问题标题】:Python pattern to replace words between single or double quotesPython模式替换单引号或双引号之间的单词
【发布时间】:2020-07-11 17:02:17
【问题描述】:

我是 Python 新手,对正则表达式很不熟悉。 我的要求是修改现有代码中的模式

我已经提取了我要修复的代码。

def replacer_factory(spelling_dict):
    def replacer(match):
        word = match.group()
        return spelling_dict.get(word, word)
    return replacer

def main():
    repkeys = {'modify': 'modifyNew', 'extract': 'extractNew'}
    with open('test.xml', 'r') as file :
        filedata = file.read()
    pattern = r'\b\w+\b' # this pattern matches whole words only
    #pattern = r'[\'"]\w+[\'"]'
    #pattern = r'["]\w+["]' 
    #pattern = '\b[\'"]\w+[\'"]\b'
    #pattern = '(["\'])(?:(?=(\\?))\2.)*?\1'

    replacer = replacer_factory(repkeys)
    filedata = re.sub(pattern, replacer, filedata)

if __name__ == '__main__':
    main()

输入

<fn:modify ele="modify">
<fn:extract name='extract' value="Title"/>
</fn:modify>

预期输出。请注意,替换词可以用单引号或双引号括起来。

<fn:modify ele="modifyNew">
<fn:extract name='extractNew' value="Title"/>
</fn:modify>

现有模式r'\b\w+\b' 导致例如&lt;fn:modifyNew ele="modifyNew"&gt;,但我正在寻找的是&lt;fn:modify ele="modifyNew"&gt;

到目前为止,我尝试的模式以 cmets 的形式给出。我很晚才意识到其中几个是错误的,前缀为 r 的字符串文字用于特殊处理反斜杠等。我仍然将它们包括在内,以回顾我迄今为止所做的任何尝试。

如果我能找到一种模式来解决这个问题,而不是改变逻辑,那就太好了。如果现有代码无法实现这一点,请同时指出。我工作的环境有Python 2.6

感谢任何帮助。

【问题讨论】:

  • 注意pattern = r'\b\w+\b' = pattern = r'\w+'
  • 所以,您说要替换的词 可以 括在单引号或双引号中,但您的意思是说它们 必须用引号括起来?
  • @WiktorStribiżew 是的。要替换的单词总是在引号内(单引号或双引号)。

标签: python regex python-2.6


【解决方案1】:

需要使用r'''(['"])(\w+)\1'''正则表达式,然后需要适配replacer方法:

def replacer_factory(spelling_dict):
    def replacer(match):
        return '{0}{1}{0}'.format(match.group(1), spelling_dict.get(match.group(2), match.group(2)))
    return replacer

您与(['"])(\w+)\1 匹配的单词是双引号或单引号,但该值在第2 组中,因此使用spelling_dict.get(match.group(2), match.group(2))。此外,引号必须放回,因此'{0}{1}{0}'.format()

Python demo

import re
def replacer_factory(spelling_dict):
    def replacer(match):
        return '{0}{1}{0}'.format(match.group(1), spelling_dict.get(match.group(2), match.group(2)))
    return replacer

repkeys = {'modify': 'modifyNew', 'extract': 'extractNew'}
pattern = r'''(['"])(\w+)\1'''
replacer = replacer_factory(repkeys)
filedata = """<fn:modify ele="modify">
<fn:extract name='extract' value="Title"/>
</fn:modify>"""
print( re.sub(pattern, replacer, filedata) )

输出:

<fn:modify ele="modifyNew">
<fn:extract name='extractNew' value="Title"/>
</fn:modify>

【讨论】:

  • 尝试解决方案。很快就会更新回来。感谢您的帮助!
猜你喜欢
  • 2012-06-11
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-12
  • 1970-01-01
  • 2017-12-29
  • 2018-11-18
相关资源
最近更新 更多