【问题标题】:Efficient use of regex with dictionary正则表达式与字典的有效使用
【发布时间】:2021-12-09 03:30:37
【问题描述】:

我有一些带有${key} 形式标签的文本文件和一个用于键的字典。标签应替换为键选择的字典中的文本。

我找到了一种使用正则表达式标记标签的方法,在字典中查找键并使用相应的字典值重建字符串。这可行,但看起来有点笨拙。而且我认为使用预编译的 rex 并避免每次迭代中的两个切片会更有效。

如何使用 Python 函数而不是手工制作的东西来实现更具可读性?

# minimal but complete example code
import re

mydic = { 'a':'alpha', 'b':'gamma' }
s = "some text about ${a} and ${b} but not ${foo}"

while True:
    sr = re.search('\${(.+?)}',s)

    if None == sr:  # could the search result be evaluated in the while clause?
        break

    key = sr.group(1)
    a,b = sr.span()
    if key in mydic:
        s = s[:a] + mydic[key] + s[b:]
    else:
        # found unkown key in ${}
        s = s[:a] + s[b:]

# output the result
s

预期结果是"some text about alpha and gamma but not "。

【问题讨论】:

    标签: python python-3.x regex


    【解决方案1】:

    如果您的文本不包含 ${ 的其他实例,除了键的开头并且没有不应该成为键的 {foo} 实例,您可以利用内置str.format_map 函数:

    from collections import defaultdict
    
    d = defaultdict(str)
    d.update(mydic)
    s = s.replace('${', '{').format_map(d)
    

    如果你想使用正则表达式,你可以使用re.sub:

    import re
    
    s = re.sub(r'\${(.+?)}', lambda m: mydic.get(m.group(1), ''), s)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      • 2016-11-22
      • 1970-01-01
      • 1970-01-01
      • 2016-04-28
      • 1970-01-01
      相关资源
      最近更新 更多