Python - 检查给定单词是否一起出现在句子列表中
假设我们有一个列表,其中包含一些短句子作为其元素。我们还有另一个列表,其中包含这些句子中使用的一些单词。我们想要找出第二个列表中的两个单词是否一起出现在第一个列表中的一些句子中。
使用 append 和 for 循环
我们使用带有 in 条件的 for 循环来检查单词在句子列表中的存在情况。然后我们使用 len 函数来检查我们是否已到达列表的末尾。
示例
list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
list_wrd = ['Eggs', 'Fruits']
print("Given list of sentences: \n",list_sen)
print("Given list of words: \n",list_wrd)
res = []
for x in list_sen:
k = [w for w in list_wrd if w in x]
if (len(k) == len(list_wrd)):
res.append(x)
print(res)输出
运行以上代码,得到以下结果:
Given list of sentences: ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday'] Given list of words: ['Eggs', 'Fruits'] ['Eggs and Fruits on Wednesday']
使用 all
在这里,我们设计了一个 for 循环来检查单词是否出现在包含句子的列表中,然后应用 all 函数来验证所有单词确实都出现在句子中。
示例
list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
list_wrd = ['Eggs', 'Fruits']
print("Given list of sentences: \n",list_sen)
print("Given list of words: \n",list_wrd)
res = [all([k in s for k in list_wrd]) for s in list_sen]
print("\nThe sentence containing the words:")
print([list_sen[i] for i in range(0, len(res)) if res[i]])运行以上代码,得到以下结果:
输出
Given list of sentences: ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday'] Given list of words: ['Eggs', 'Fruits'] The sentence containing the words: ['Eggs and Fruits on Wednesday']
使用 lambda 和 map
我们可以采用与上述类似的方法,但使用 lambda 和 map 函数。我们还使用 split 函数并检查所有给定单词在包含句子的列表中的可用性。map 函数用于再次将此逻辑应用于列表的每个元素。
示例
list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
list_wrd = ['Eggs', 'Fruits']
print("Given list of sentences: \n",list_sen)
print("Given list of words: \n",list_wrd)
res = list(map(lambda i: all(map(lambda j:j in i.split(),
list_wrd)), list_sen))
print("\nThe sentence containing the words:")
print([list_sen[i] for i in range(0, len(res)) if res[i]])输出
运行以上代码,得到以下结果:
Given list of sentences: ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday'] Given list of words: ['Eggs', 'Fruits'] The sentence containing the words: ['Eggs and Fruits on Wednesday']
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP