2014-10-19 67 views
-2
test_string = ("this is a test") 

test_list = [dog, cat, test, is, water] 

我如何看待'this'或'是'或'a'或'test'是否在test_list中?如何检查字符串中的单词是否是列表或列表中的元素?

+0

的可能重复[如何检查是否字符串包含在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

+0

不应该test_list = [dog,cat,test,is,water]而不是test_list = ['狗','猫','测试','是','水']? – tagoma 2014-10-19 22:21:10

+0

是的,我经常犯这个错误。 – 2014-10-21 11:13:56

回答

0

使用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 
0

您可以使用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 
+0

nope,你遍历每个字符不是每个字 – 2014-10-19 22:05:51

+0

我遍历列表中的每个项目,并检查它是否在字符串中。 – Parker 2014-10-19 22:08:42

+0

尝试's =“这是一个测试”print(“th”in s)' – 2014-10-19 22:10:33

0

什么你问的是交集仅仅是空的。

>>> set(test_string.split(' ')).intersection(set(test_list)) 
set(['test', 'is']) 
0

一种选择是正则表达式,如

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 
相关问题