检查另一个字符串中的单词列表[重复]
- 2025-04-16 08:56:00
- admin 原创
- 14
问题描述:
我可以在 python 中做这样的事情:
l = ['one', 'two', 'three']
if 'some word' in l:
...
这将检查列表中是否存在“某个单词”。但我可以反过来做吗?
l = ['one', 'two', 'three']
if l in 'some one long two phrase three':
...
我需要检查数组中的某些单词是否在字符串中。我可以使用循环来实现,但这种方法需要更多代码行。
解决方案 1:
if any(word in 'some one long two phrase three' for word in list_):
解决方案 2:
这里有几种替代方法,根据具体情况,可能比 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 conceptual”中找到单词“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 的解决方案。
解决方案 3:
如果您的单词列表很长,并且您需要多次进行此测试,则可能值得将列表转换为集合并使用集合交集进行测试(额外的好处是您将获得两个列表中的实际单词):
>>> 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'])
解决方案 4:
解决这个问题最简单、最简单的方法是使用
import re
search_list = ['one', 'two', 'there']
long_string = 'some one long two phrase three'
if re.compile('|'.join(search_list),re.IGNORECASE).search(long_string): #re.IGNORECASE makes the search case-insensitive
# Do Something if word is present
else:
# Do Something else if word is not present
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD