基于 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
- 如果 i 存在于 cnt 中,则
- 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']
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
['efficient', 'durable', 'strong']
广告