检查单词在单词列表中的子串匹配
我想检查一个单词是否在一个单词列表里。
word = "with"
word_list = ["without", "bla", "foo", "bar"]
我试过用 if word in set(list)
,但是结果不太对,因为 in
是在匹配字符串,而不是单个项目。也就是说,像 "with"
这样的单词在 word_list
中的任何单词里都能找到,但如果我用 if "with" in set(list)
,它还是会返回 True
。
有没有比手动遍历 list
更简单的方法来做这个检查呢?
3 个回答
0
你也可以通过把所有的单词从word_list合并成一个字符串,来创建一个搜索字符串:
word = "with"
word_list = ' '.join(["without", "bla", "foo", "bar"])
然后只需要用一个简单的in
测试就可以完成这个任务:
return word in word_list
3
in
用于检查完全匹配时是正常工作的:
>>> word = "with"
>>> mylist = ["without", "bla", "foo", "bar"]
>>> word in mylist
False
>>>
你也可以使用:
milist.index(myword) # gives error if your word is not in the list (use in a try/except)
或者
milist.count(myword) # gives a number > 0 if the word is in the list.
不过,如果你想查找子字符串,那么:
for item in mylist:
if word in item:
print 'found'
break
顺便说一下,不要把list
用作变量名
9
你可以这样做:
found = any(word in item for item in wordlist)
这个代码会检查每一个单词,如果有任何一个单词匹配,就会返回“真”,也就是表示找到了匹配的单词。