Python 如何检查字符串中的单词是否是列表中的元素?
如何查看“this”或“is”或“a”或“test”是否在测试列表中?用于拆分字符串,并使用查看字符串中的任何单词是否在您的列表中:Python 如何检查字符串中的单词是否是列表中的元素?,python,Python,如何查看“this”或“is”或“a”或“test”是否在测试列表中?用于拆分字符串,并使用查看字符串中的任何单词是否在您的列表中: test_string = ("this is a test") test_list = [dog, cat, test, is, water] 你可以用任何一种 inlist=test_string.split中的元素的test_列表中的任意元素 inlist将为True或False,具体取决于它是否在列表中 例如: test_string = ("thi
test_string = ("this is a test")
test_list = [dog, cat, test, is, water]
你可以用任何一种
inlist=test_string.split中的元素的test_列表中的任意元素
inlist将为True或False,具体取决于它是否在列表中
例如:
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
你要问的是集合交点是否为非空
>>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
一种选择是正则表达式,例如
>>> set(test_string.split(' ')).intersection(set(test_list))
set(['test', 'is'])
可能重复的不应该测试列表=[狗,猫,测试,是,水]而是测试列表=[狗,猫,测试,是,水]?是的,我很匆忙,我经常犯这个错误。谢谢你的提醒eduardnope,你在迭代每个字符,而不是每个单词。我在迭代列表中的每个项目,并检查它是否在字符串中。try s=这是sI解释的OP问题中的测试打印,因为他们只是想看看列表中是否有任何元素出现,他们没有澄清。如果OP想要检查一个完整的单词是否匹配,你是对的。我认为很明显他们想要匹配一个完整的单词
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