【发布时间】: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