如何检查字符串中的单词是列表中的元素还是列表?

时间:2014-10-19 21:59:05

标签: python

test_string = ("this is a test")

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

如何查看'this'或'is'或'a'或'test'是否在test_list中?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:0)

你要问的是集合交叉点是否非空。

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

答案 3 :(得分: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