我有一些帶有標簽的文本檔案${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 "。
uj5u.com熱心網友回復:
如果您的文本${在鍵的開頭不包含其他實體,并且沒有{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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/334546.html
