2013-07-18 23 views
5

我有一個腳本運行到我的文本中,並搜索並替換所有基於數據庫編寫的句子。搜索並替換爲「僅整個字」選項

腳本:

with open('C:/Users/User/Desktop/Portuguesetranslator.txt') as f: 
    for l in f: 
     s = l.split('*') 
     editor.replace(s[0],s[1]) 

和數據庫例如:

Event*Evento* 
result*resultado* 

等等......

現在正在發生的事情是我需要的 「全字」在那個腳本中,因爲我發現自己有問題。

例如與ResultEvent,因爲當我更換了ResultadoEvento,我運行腳本文本一次腳本再次更換ResultadoEvento

而我運行腳本後的結果仍然是這樣的ResultadoadoEventoo

只是讓你們知道。其不僅對事件和結果,還有,我已經設置了搜索和替換工作更多然後1000+句子..

我不需要simples搜索並替換爲兩個單詞..因爲我要一遍又一遍地編輯數據庫以用於不同的句子..

+0

是'editor'一個字符串? – kindall

回答

5

使用re.sub而不是普通字符串替換來替換整個單詞。因此,即使它的腳本再次運行將不會取代已經被替換的單詞。

>>> import re 
>>> editor = "This is result of the match" 
>>> new_editor = re.sub(r"\bresult\b","resultado",editor) 
>>> new_editor 
'This is resultado of the match' 
>>> newest_editor = re.sub(r"\bresult\b","resultado",new_editor) 
>>> newest_editor 
'This is resultado of the match' 
+0

我在哪裏取代 –

+0

只是爲了指出..即時通訊全新的編碼和東西, –

+0

只是讓你知道..數據庫包含超過1400字..和結果和事件只是例子.. –

11

你想要一個正則表達式。您可以使用令牌\b來匹配單詞邊界:即\bresult\b只會匹配確切的單詞「結果」。

import re 

with open('C:/Users/User/Desktop/Portuguesetranslator.txt') as f: 
    for l in f: 
     s = l.split('*') 
     editor = re.sub(r"\b%s\b" % s[0] , s[1], editor) 
+0

我應該替換爲我目前的腳本?在數據庫中,我應該在每個單詞前添加\ b? –

+0

例如\ bresult * \ bresultado *? –

+1

只需用你的代碼替換你的代碼......腳本添加了'\ b's,所以你不必在「數據庫」中包含它們。 – kindall

7

使用re.sub

replacements = {'the':'a', 
       'this':'that'} 

def replace(match): 
    return replacements[match.group(0)] 

# notice that the 'this' in 'thistle' is not matched 
print re.sub('|'.join(r'\b%s\b' % re.escape(s) for s in replacements), 
     replace, 'the cat has this thistle.') 

打印

a cat has that thistle. 

注:

  • 所有字符串被替換爲joine d變成一個模式,所以 該字符串需要循環一次。

  • 將源字符串傳遞給re.escape以避免 將它們解釋爲正則表達式。

  • 單詞被r'\b'包圍,以確保匹配的結果僅用於 整個單詞。

  • 使用替換函數,以便可以替換任何匹配項。

1

這很簡單。使用re.sub,不要使用replace。

import re 
replacements = {r'\bthe\b':'a', 
       r'\bthis\b':'that'} 

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

replace_all("the cat has this thistle.", replacements) 

它將打印

a cat has that thistle.