2015-12-17 63 views
1

注意,這不是這個問題的一個副本:獲取關鍵字串從字符串列表在Python

How to check if a string contains an element from a list in Python

然而,它是基於它的邏輯。

我有以下字符串:

my_string = 'this is my complex description' 

我有一個關鍵字列表:

keywords = ['my', 'desc', 'complex'] 

我知道我可以使用以下方法來檢查是否存在關鍵字:

if any(ext in my_string for ext in keywords): 
    print(my_string) 

但我想顯示哪些關鍵字實際上符合描述。我知道我可以通過關鍵字進行循環,然後逐個檢查每個關鍵字,但是可以在一個語句中進行檢查嗎?

python是哪個版本的解決方案並不重要。

+0

您可以使用匹配關鍵字構建列表comp。 '匹配= [關鍵字的關鍵字在關鍵字如果關鍵字在my_string]''。 –

回答

4

如果要匹配完整的單詞,你可以使用交集:

>>> my_string = 'this is my complex description' 
>>> keywords = ['my', 'desc', 'complex'] 
>>> set(my_string.split()) & set(keywords) 
{'complex', 'my'} 
+0

該解決方案效果很好。謝謝。 – CodeLikeBeaker

1
>>> my_string = 'this is my complex description' 
>>> keywords = ['my', 'desc', 'complex'] 
>>> print(*[c for c in my_string.split() if c in keywords]) 
my complex 

注意:此這隻作品,據我所知,在python3.x(我不太確定它是如何站在蟒蛇2)

如果你困惑於它在做什麼,*只是將列表解析製作的列表解壓縮,將列表理解過濾爲my_string中的任何ISNT作爲print中的單獨參數。在python3中,print中的單獨參數在它們之間打印有空格。

0
found_words = [ word for word in keywords if word in my_string ] 

這會給你在my_string發現關鍵字的列表。性能會更好,如果你做的關鍵字set雖然:

keywords = set(['my', 'desc', 'complex']) 
found_words = [ word for word in my_string.split() if word in keywords ] 

但後者依賴於一個事實,即my_string沒有單獨的詞與除空白,任何東西。