基於 Python 統計詞語出現次數並排序的程式


假設,我們有兩個列表;'phrases' 包含一些選定的短語,'sentences' 包含一些句子,這些句子可能包含也可能不包含來自另一個列表的短語。我們需要找出第一個列表中的各個短語是否出現在第二個列表中,並根據它們在第二個列表中的出現次數對第一個列表中的短語進行排序。我們將排序後的列表 'phrases' 作為輸出返回。

因此,如果輸入類似於 phrases = ['strong', 'durable', 'efficient'],sentences = ['the product is durable and efficient', 'strong and durable', 'it is efficient', 'like it because it is efficient'],則輸出將為 ['efficient', 'durable', 'strong']

短語 'efficient' 出現在句子 0、2 和 4 中。它的出現次數最多,因此它位於輸出的開頭。短語 'durable' 和 'strong' 分別出現在句子 0 和 1,以及 1 中。因此,這些短語在輸出中佔據接下來的位置。

為了解決這個問題,我們將遵循以下步驟:

  • cnt := 一個新的對映
  • 對於 phrases 中的每個 feature,執行以下操作:
    • cnt[feature] := 0
  • 對於 sentences 中的每個 response,執行以下操作:
    • p := 一個包含 response 中單詞的新列表
    • s := 來自 p 的一個新集合
    • 對於 s 中的每個 i,執行以下操作:
      • 如果 i 存在於 cnt 中,則
        • cnt[i] := cnt[i] + 1
  • res := 一個包含每個 k 在 cnt 中的 (k, cnt[k]) 對的新列表
  • 根據計數 k 對列表 res 進行排序
  • 返回列表 res,不包括計數值 k

示例

讓我們看看以下實現以獲得更好的理解:

def solve(phrases, sentences):
   cnt = {}
   for feature in phrases:
      cnt[feature] = 0
   for response in sentences:
      p = response.split()
      s = set(p)
      for i in s:
         if i in cnt:
            cnt[i] += 1
   res = [[k, cnt[k]] for k in cnt]
   res.sort(key = lambda x:(-x[1], phrases.index(x[0])))
   return [i[0] for i in res]

print(solve(['strong', 'durable', 'efficient'], ['the product is durable and efficient', 'strong and durable', 'it is efficient', 'like it because it is efficient']))

輸入

['strong', 'durable', 'efficient'],
['the product is durable and efficient', 'strong and durable', 'it is
efficient', 'like it because it is efficient']

輸出

['efficient', 'durable', 'strong']

更新於: 2021年10月7日

91 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.