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']

更新於: 2020-07-10

1K+ 閱讀量

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.