2015-08-28 22 views
0

此函數使用顏色突出顯示某個字符串中的某些關鍵字。 Fore.CYANFore.RESET來自Colorama模塊。Untangle re.findall捕獲組:'list'對象沒有屬性'join'

有沒有辦法插入regex而不是列表["This", "words", "annotate"]

from colorama import Fore 

def highlight(var, keywords): 
    replacement = Fore.CYAN + "\\1" + reset() 
    var = re.sub("(" + "|".join(map(re.escape, keywords)) + ")", replacement, var, re.I) 
     print var + Fore.RESET 

string = "This string contains words to annotate" 

highlight(string, ["This", "words", "annotate"]) 

我已經試過這樣:

regex_keywords = re.findall(r"(This)|(Words)|(Annotate)", string, re.I) 

highlight(string, regex_keywords) 

,因爲它抱怨'list' object has no attribute 'join'"不工作。

+1

我不明白你要做什麼。你能展示一些樣本輸入和輸出嗎? – Cyphase

+0

@Cyphase感謝您的詢問。我試圖使用正則表達式規則而不是'[「This」,「words」,「annotate」]''。這可以提高關鍵字的靈活性。 – Winterflags

+0

這是一個細節;你想做什麼_? :)你想用這個代碼來完成什麼?如果您可以顯示一些示例輸入和輸出,它將非常有用。 – Cyphase

回答

1

higlight需要對字符串進行任何迭代。你有一個字符串元組列表的列表。刪除括號並忘記元組:

regex_keywords = re.findall(r"This|Words|Annotate", string, re.I) 
highlight(string, regex_keywords) 
+0

感謝,但是,給出'AttributeError:(「'列表'對象沒有屬性'join'」'我將編輯出問題的元組轉換 – Winterflags

+0

@Winterflags:沒有看到正則表達式中的圓括號。 – Daniel

+0

非常感謝您的支持!我沒有意識到我應該這樣做,而不會捕獲組,應該儘早嘗試:) – Winterflags

相關問題