根据短语在 Python 中的出现情况对短语进行排序的程序

pythonserver side programmingprogramming更新于 2025/12/9 21:32:17

假设我们有两个列表;"短语"包含一些选定的短语,"句子"包含几个句子,这些句子可能包含也可能不包含另一个列表中的短语。我们必须找出第一个列表中的各个短语是否出现在第二个列表中,并根据它们在第二个列表中的出现情况对第一个列表中的短语进行排序。我们返回排序后的列表"短语"作为输出。

因此,如果输入为 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 := 一个新的映射
  • 对于短语中的每个特征,执行
    • cnt[feature] := 0
  • 对于句子中的每个响应,执行
    • p := 一个包含响应单词的新列表
    • s := 来自 p 的新集合
    • 对于 s 中的每个 i,执行
      • 如果 i 存在于 cnt 中,则
        • cnt[i] := cnt[i] + 1
  • res := 一个新列表,其中包含 cnt 中每个 k 的对 (k, cnt[k])
  • 根据计数 k 对列表 res 进行排序
  • 返回不包含计数值 k 的列表 res

示例

让我们看看下面的实现以便更好地理解 −

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

相关文章


有用资源