gpt4 book ai didi

python - 在不使用包 ADT 上的计数器类的情况下计算词频的最简单方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:52:04 30 4
gpt4 key购买 nike

我有一些代码可以使用计数器类导入在选定列表上很好地计算词频。

from collections import Counter

terms=['the', 'fox', 'the', 'quick', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

tf = Counter(terms)

print(tf)

现有代码运行良好,但我想知道在没有 python 计数器类帮助的情况下严格使用 bag/multiset ADT 实现相同结果的最精简方法是什么。

我花了几天时间试验代码并查看其他论坛,但没有取得太大成功。

最佳答案

您可以使用单个字典理解:

terms=['the', 'fox', 'the', 'quick', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
new_terms = {term:terms.count(term) for term in terms}

输出:

{'lazy': 1, 'over': 1, 'fox': 2, 'dog': 1, 'quick': 1, 'the': 3, 'jumps': 1}

使用multiset:

import itertools
import multiset
final_data = [multiset.Multiset(list(b)) for a, b in itertools.groupby(sorted(terms))]

输出:

[Multiset({'dog': 1}), Multiset({'fox': 2}), Multiset({'jumps': 1}), Multiset({'lazy': 1}), Multiset({'over': 1}), Multiset({'quick': 1}), Multiset({'the': 3})]

关于python - 在不使用包 ADT 上的计数器类的情况下计算词频的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47597545/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com