此函數使用顏色突出顯示某個字符串中的某些關鍵字。 Fore.CYAN
和Fore.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'"
不工作。
我不明白你要做什麼。你能展示一些樣本輸入和輸出嗎? – Cyphase
@Cyphase感謝您的詢問。我試圖使用正則表達式規則而不是'[「This」,「words」,「annotate」]''。這可以提高關鍵字的靈活性。 – Winterflags
這是一個細節;你想做什麼_? :)你想用這個代碼來完成什麼?如果您可以顯示一些示例輸入和輸出,它將非常有用。 – Cyphase