2011-08-24 103 views
1

我想替換包含以下單詞的字符串部分「$%word $%」 我想用字典的值替換它,其中相應的鍵等於單詞。用於字符串替換的python正則表達式

換句話說,如果我有一個字符串: 「blahblahblah $%一句話$%blablablabla $%汽車$%」 和字典{一句話: '日wassup',汽車: '豐田'}

字符串將是「blahblahblah wassup blablablabla豐田」

你怎麼能在Python中實現它,我想使用字符串替換和正則表達式。

回答

7

使用re.sub與函數作爲REPL參數:

import re 

text = "blahblahblah $%word$% blablablabla $%car$%" 
words = dict(word="wassup", car="toyota") 

def replacement(match): 
    try: 
     return words[match.group(1)] # Lookup replacement string 
    except KeyError: 
     return match.group(0) # Return pattern unchanged 

pattern = re.compile(r'\$%(\w+)\$%') 
result = pattern.sub(replacement, text) 

如果你想通過替換表在使用re.sub的時候,使用functools.partial

import functools 

def replacement(table, match): 
    try: 
     return table[match.group(1)] 
    except: 
     return match.group(0) 

table = dict(...) 
result = pattern.sub(functools.partial(replacement, table), text) 

...或實施__call__的課程:

class Replacement(object): 
    def __init__(self, table): 
     self.table = table 
    def __call__(self, match): 
     try: 
      return self.table[match.group(1)] 
     except: 
      return match.group(0) 

result = pattern.sub(Replacement(table), text) 
+0

如果字典是另一種方法創建什麼?我將如何實施更換?我無法將參數添加到替換中。 – mabounassif

+0

與此問題非常相似; http://stackoverflow.com/questions/7182546/how-to-replace-the-nth-appearance-of-a-needle-in-a-haystack-python –

+0

@mabounassif - Let'replacement' take the dictionary作爲參數,然後使用'functools.partial()'創建一個傳遞字典的單參數包裝函數。我會更新我的答案來舉一個例子。 –

0

re模塊是你想要的。

雖然您可能想重新考慮您選擇的分隔符。 $%可能會有問題,因爲$是正則表達式中的保留字符。儘管如此,只要記住在模式中使用'\\$'r'\$'(這是一個原始字符串,非常有用,如果你在python中執行正則表達式的東西)。

1
import re 

text = "blahblahblah $%word$% blablablabla $%car$%" 
words = dict(word="wassup", car="toyota") 

regx = re.compile('(\$%%(%s)\$%%)' % '|'.join(words.iterkeys())) 

print regx.sub(lambda mat: words[mat.group(2)], text) 

結果

blahblahblah wassup blablablabla toyota