test_string = ("this is a test")
test_list = [dog, cat, test, is, water]
我如何看待'this'或'是'或'a'或'test'是否在test_list中?如何檢查字符串中的單詞是否是列表或列表中的元素?
test_string = ("this is a test")
test_list = [dog, cat, test, is, water]
我如何看待'this'或'是'或'a'或'test'是否在test_list中?如何檢查字符串中的單詞是否是列表或列表中的元素?
使用str.split分割字符串,並使用any,看看是否有任何字符串中的話您的列表:
test_string = ("this is a test")
test_list = ["dog", "cat", "test", "is","water"]
print(any(x in test_list for x in test_string.split()))
In [9]: test_string = ("this is a test")
In [10]: test_string.split()
Out[10]: ['this', 'is', 'a', 'test'] # becomes a list of individual words
您可以使用any
這個
inlist = any(ele in test_list for ele in test_string.split())
inlist
將是真或假,取決於它是否在列表中。
例子:
>>test_string = ("this is a test")
>>test_list = ['dog', 'cat', 'water']
>>inlist = any(ele in test_string for ele in test_list)
>>print inlist
False
>>test_string = ("this is a test")
>>test_list = ['dog', 'cat', 'is', 'test' 'water']
>>inlist = any(ele in test_string for ele in test_list)
>>print inlist
True
nope,你遍歷每個字符不是每個字 – 2014-10-19 22:05:51
我遍歷列表中的每個項目,並檢查它是否在字符串中。 – Parker 2014-10-19 22:08:42
嘗試's =「這是一個測試」print(「th」in s)' – 2014-10-19 22:10:33
什麼你問的是交集僅僅是空的。
>>> set(test_string.split(' ')).intersection(set(test_list))
set(['test', 'is'])
一種選擇是正則表達式,如
import re
# Test string
test_string = 'this is a test'
# Words to be matched
test_list = ['dog', 'cat', 'test', 'is', 'water']
# Container for matching words
yes = []
# Loop through the list of words
for words in test_list:
match = re.search(words, test_string)
if match:
yes.append(words)
# Output results
print str(yes) + ' were matched'
#['test', 'is'] were matched
的可能重複[如何檢查是否字符串包含在Python列表中的元素(http://stackoverflow.com/questions/6531482/how-to-check-if-a-string-contains-an-element-from-a-list-in-python) – Parker 2014-10-19 22:05:24
不應該test_list = [dog,cat,test,is,water]而不是test_list = ['狗','貓','測試','是','水']? – tagoma 2014-10-19 22:21:10
是的,我經常犯這個錯誤。 – 2014-10-21 11:13:56