2016-12-01 40 views
0

我希望做一些特殊的應用re.sub 輸入特殊應用re.sub python3

string = "\"hope\" and \"love\" or \"passion\" and (\"luck\" or \"money\") " 
word_list = ['hope', 'love', 'passion', 'money', 'luck'] 

的希望輸出

'0 and 1 or 2 and (4 or 3) 

我嘗試用

print(re.sub("\"([^\"]*)\"", stri.index(r'\g<1>') , string)) 

但dosen't work

+0

請不要轉義所有內容,請使用單引號。 –

回答

0

可選地(無re),可能會使用enumerateword_list迭代,並使用str.replace()取代string的內容爲:

my_string = "\"hope\" and \"love\" or \"passion\" and (\"luck\" or \"money\") " 
word_list = ['hope', 'love', 'passion', 'money', 'luck'] 

for i, word in enumerate(word_list): 
    my_string = my_string.replace('"{}"'.format(word), str(i)) 

通過my_string最後值保持將是:

'0 and 1 or 2 and (4 or 3) ' 
0

不考慮您的單詞列表,您可以使用itertools.count來計算匹配數量和函數作爲sub()函數的第二個參數,該函數調用每個匹配的計數器的next

In [10]: from itertools import count 

In [11]: c = count() 

In [12]: re.sub(r'"([^"]+)"', lambda x: str(next(c)), string) 
Out[12]: '0 and 1 or 2 and (3 or 4) ' 

如果你想指數是基於詞的索引中word_list作爲一種有效的方法,您可以創建自話的關鍵一本字典和索引的值,則使用一個簡單的索引,以獲得相應的索引內sub()功能:

In [29]: word_dict = {w: str(i) for i, w in enumerate(word_list)} 

In [30]: re.sub(r'"([^"]+)"', lambda x: word_dict[x.group(1)], string) 
Out[30]: '0 and 1 or 2 and (4 or 3) ' 

請注意,您可以使用list.index方法,以獲取字的索引每個單詞。但由於列表索引的複雜性是O(n),因此不如使用O(1)的字典索引那樣高效。

+0

它是有趣的,它的工作原理,但我不明白x的作用是什麼。group(1) –

+0

@SlimaneMEHARZI它會給你每個匹配的第一個捕獲組,它將是捕獲組([[^「] +')之間的正則表達式匹配的字符串。 – Kasramvd

0

使用re.sub函數與替換函數作爲第二個參數:

string = "\"hope\" and \"love\" or \"passion\" and (\"luck\" or \"money\") " 
word_list = ['hope', 'love', 'passion', 'money', 'luck'] 

print(re.sub("\"([^\"]*)\"", lambda m: 
    str(word_list.index(m.group(1))) if m.group(1) in word_list else m.group(1), string)) 

輸出:

0 and 1 or 2 and (4 or 3) 

記住,有可能是其不在word_list列表,如火柴... (\"luck\" or \"money\") or \"compassion\"

應用re.sub(圖案,REPL,串,計數= 0,標誌= 0)

... 如果REPL是一個函數,它被稱爲爲每個非重疊 發生模式。該函數採用單個匹配對象 參數,並返回替換字符串。