簡體   English   中英

特殊的re.sub python3

[英]Special re.sub python3

我想做一些特殊的re.sub輸入

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))

但這沒用

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列表中沒有的匹配word_list ,例如... (\\"luck\\" or \\"money\\") or \\"compassion\\"

re.sub (模式,REPL,字符串,計數= 0,標志= 0)

...如果repl是一個函數,則每次非重疊出現的模式都會調用它。 該函數采用單個match對象參數,並返回替換字符串。

不考慮你的單詞列表,你可以使用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)的效率。

另外(沒有re ),您可以使用enumerate遍歷word_list使用word_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) '

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM