检查字符串中单词列表
我可以在Python中这样做:
l = ['one', 'two', 'three']
if 'some word' in l:
...
这段代码会检查“某个词”是否在列表里。但是我能不能做反向的操作呢?
l = ['one', 'two', 'three']
if l in 'some one long two phrase three':
...
我需要检查数组中的一些词是否在一个字符串里。我可以用循环来做到这一点,但这样代码会写得比较多。
4 个回答
26
如果你的单词列表很长,而且你需要多次进行这个测试,那么把这个列表转换成一个集合可能会更划算。这样做的好处是,你可以使用集合的交集来进行测试,这样还能得到两个列表中实际存在的单词:
>>> long_word_list = 'some one long two phrase three about above along after against'
>>> long_word_set = set(long_word_list.split())
>>> set('word along river'.split()) & long_word_set
set(['along'])
34
这里有几种不同的方法可以实现这个功能,根据具体情况,可能比KennyTM的答案更快或更合适。
1) 使用正则表达式:
import re
words_re = re.compile("|".join(list_of_words))
if words_re.search('some one long two phrase three'):
# do logic you want to perform
2) 如果你想匹配完整的单词,比如不想在“them theorems are theoretical”这句话中找到“the”这个词,可以使用集合:
word_set = set(list_of_words)
phrase_set = set('some one long two phrase three'.split())
if word_set.intersection(phrase_set):
# do stuff
当然,你也可以使用正则表达式中的“\b”符号来匹配完整的单词。
这些方法和Kenny的解决方案的性能会受到几个因素的影响,比如单词列表和短语字符串的长度,以及它们变化的频率。如果性能不是问题,那就选择最简单的方法,可能就是Kenny的方案。
399
在编程中,有时候我们会遇到一些问题,可能是因为代码写得不够好,或者是我们对某些概念理解得不够透彻。比如,有人可能在使用某个工具或者库的时候,遇到了错误或者不明白的地方。这种时候,大家通常会去像StackOverflow这样的论坛寻求帮助。
在这些论坛上,很多人会分享他们的经验和解决方案。比如,有人可能会问:“我在运行我的程序时遇到了这个错误,应该怎么解决?”然后其他人就会根据自己的经验,给出一些建议或者解决办法。
总之,编程的过程中,遇到问题是很正常的,关键是要学会如何寻找帮助和解决问题的办法。
if any(word in 'some one long two phrase three' for word in list_):