Python - 检查给定的单词是否一起出现在句子列表中

pythonserver side programmingprogramming更新于 2025/8/1 1:16:17

假设我们有一个包含小句子作为其元素的列表。我们有另一个列表,其中包含第一个列表的这些句子中使用的一些单词。我们想要找出第二个列表中的两个单词是否一起出现在第一个列表的某些句子中。

使用附加和 for 循环

我们使用带有 in 条件的 for 循环来检查句子列表中是否存在单词。然后我们使用 len 函数检查是否已到达列表末尾。

示例

list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
list_wrd = ['Eggs', 'Fruits']

print("给定句子列表: \n",list_sen)
print("给定单词列表: \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)

输出

运行上述代码得到以下结果 −

给定句子列表:
['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
给定单词列表:
['Eggs', 'Fruits']
['Eggs and Fruits on Wednesday']

使用全部

在这里,我们设计了一个 for 循环来检查单词是否存在于包含句子的列表中,然后应用 all 函数来验证句子中确实存在所有单词。

示例

list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
list_wrd = ['Eggs', 'Fruits']

print("给定句子列表: \n",list_sen)
print("给定单词列表: \n",list_wrd)

res = [all([k in s for k in list_wrd]) for s in list_sen]
print("\n包含单词的句子:")
print([list_sen[i] for i in range(0, len(res)) if res[i]])

运行上述代码得到以下结果 −

输出

给定句子列表:
['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
给定单词列表:
['Eggs', 'Fruits']

包含单词的句子:
['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("给定句子列表: \n",list_sen)

print("给定单词列表: \n",list_wrd)

res = list(map(lambda i: all(map(lambda j:j in i.split(),
list_wrd)), list_sen))

print("\n包含单词的句子:")
print([list_sen[i] for i in range(0, len(res)) if res[i]])

输出

运行上述代码得到以下结果 −

给定句子列表:
['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
给定单词列表:
['Eggs', 'Fruits']

包含单词的句子:
['Eggs and Fruits on Wednesday']

相关文章


有用资源