2013-05-13 172 views
0

我有一個字典字符串被替換爲keys及其替換作爲值。除了用標記來查看字符串標記外,還有更好/更快的替換方法嗎?將替換字符串替換爲鍵並將替換字符串替換爲值。蟒蛇

我已經做了這樣:

segmenter = {'foobar':'foo bar', 'withoutspace':'without space', 'barbar': 'bar bar'} 

sentence = "this is a foobar in a barbar withoutspace" 

for i in sentence.split(): 
    if i in segmenter: 
    sentence.replace(i, segmenter[i]) 
+1

我問[同樣的問題(http://stackoverflow.com/q/10931150/989121)前一陣子的功能。有一些很好的答案。 – georg 2013-05-13 10:00:51

回答

5

字符串在Python是不可改變的。所以,str.replace返回一個新的字符串,而不是修改原始字符串。您可以使用str.join()和列表理解這裏:

>>> segmenter = {'foobar':'foo bar', 'withoutspace':'without space', 'barbar': 'bar bar'} 
>>> sentence = "this is a foobar in a barbar withoutspace" 

>>> " ".join([ segmenter.get(word,word) for word in sentence.split()]) 
'this is a foo bar in a bar bar without space' 

str.replace的另一個問題是,它也將與

"abar barb"更換的話就像"abarbarb"

4

re.sub可以調用返回的替代

segmenter = {'foobar':'foo bar', 'withoutspace':'without space', 'barbar': 'bar bar'} 
sentence = "this is a foobar in a barbar withoutspace" 

import re 

def fn(match): 
    return segmenter[match.group()] 

print re.sub('|'.join(re.escape(k) for k in segmenter), fn, sentence) 
+1

+1這比split/get/join方法更具慣用和可控性。 One nit:在構建這樣的組合正則表達式時,一定要按鍵長進行降序排序,以便像「without」這樣的較長鍵不會被像「with」這樣的較短鍵所掩蓋。或者,使用「\ b」來定位字邊界並防止鍵之間的混疊。 – 2013-05-13 08:13:49