2017-03-18 43 views
0

我使用下面的代碼來查找字符串中「< <」和「>>」所包含的任何單詞,並將它們替換爲先前定義的相關變量。這有效,但有沒有更安全或更有效的方法來實現這一目標?我已經看到了幾個有關使用eval的警告,我的解決方案看起來過於複雜。如何用Python替換字符串中的動態變量

import re 

aa = 'alpha' 
bb = 'beta' 
cc = 'gamma' 

teststr = 'A for <<aa>>, b means <<bb>>, and c could be <<cc>>.' 

matches = re.finditer('<<(\w*)>>', teststr) 

for i in matches: 
    teststr = teststr.replace(i.group(0), eval(i.group(1))) 

print teststr 

回答

1

使用字典和lambda函數作爲替代:

>>> import re 
>>> teststr = 'A for <<aa>>, b means <<bb>>, and c could be <<cc>>.' 
>>> dico = { 'aa':'alpha', 'bb':'beta', 'cc':'gamma' } 
>>> re.sub(r'<<([^>]*)>>', lambda m: dico[m.group(1)], teststr) 
'A for alpha, b means beta, and c could be gamma.' 

如果你不能確定<<>>之間的每個字符串存在在詞典中的關鍵,改變[^>]*與所有的交替可用密鑰:aa|bb|cc。如果你有很多按鍵,你不想手工製作,您可以動態生成模式是這樣的:

蟒蛇2.7:

>>> re.sub(r'<<(%s)>>'%"|".join(sorted(dico.keys(), reverse=True)), lambda x: dico[x.group(1)], teststr) 

蟒蛇3.X:

>>> re.sub(r'<<({})>>'.format("|".join(sorted(dico.keys(), reverse=True))), lambda x: dico[x.group(1)], teststr) 
0

使用字典來獲得替代。

import re 
d = {'aa': 'alpha', 'bb': 'beta', 'cc': 'gamma'} 

teststr = 'A for <<aa>>, b means <<bb>>, and c could be <<cc>>.' 
matches = re.finditer('<<(\w*)>>', teststr) 
for i in matches: 
    teststr = teststr.replace(i.group(0), d[i.group(1)]) 
print(teststr) 

打印A for alpha, b means beta, and c could be gamma.

相關問題