2014-07-07 44 views
0

有一個很簡單的功能從字典替換:與Python不需要的部分匹配替換

def replace_all(text, dic): 
    for i, j in dic.iteritems(): 
     text = text.replace(i, j) 
    return text 

我打電話的熊貓數據幀列此功能。可能是一個列表或任何其他,這只是我的例子現在) 下面是數據框的例子:

**root** 
P1 
P2 
P10 

我想獲得最終是這樣的:

**root** **gen** 
P1   bob 
P2   jack 
P10  mike 

因此,我很使用這個小函數與字典

gen={"P1":"bob", "P2":"jack", "P10":"mike"} 
df['gen']=df['root'].apply(lambda x : replace_all(x,gen)) 

這工作沒有錯誤消息,但我得到部分匹配。

**root** **gen** 
P1   bob 
P2   jack 
P10  bob0 

它把P10換成了P1,這是有道理的,但是如何防止呢?

感謝

回答

1

str.replace方法是做什麼的文檔說,它應該做的... :-p

嘗試將您的replace_all函數更改爲:

def replace_all(text, dic): 
    return dic.get(text, text) 

dict.get(key, default)方法返回dict[key]key in dict,否則返回default

0

這是因爲str.replace()將取代「串」在字符串中隨處可見。

參見:str.replace

選項:

  1. 使用正則表達式匹配和替換。
  2. 匹配整個字符串並替換。
0

更換text = text.replace(i, j)text = dic[text]

+0

如果'text not in dic'不起作用。應該使用'dic.get(text,text)'代替。 –

0

由於replace將查找字符串的任何部分,認爲這是一種替代方案:

>>> text = 'Hello P1 this is P2 with P10' 
>>> d = {'P1': 'world', 'P2': 'peanut', 'P10': 'butter'} 
>>> ' '.join(d.get(i, i) for i in text.split()) 
'Hello world this is peanut with butter' 
+0

如果OP真的想替換整個單詞,這是一個很好的方法,但我認爲他只是想替換整個字符串...... –