get到python里的一个类---Counter

本文介绍了Python中collections模块下的Counter类,通过实例演示了如何使用Counter来统计字符串中各字符出现的次数。
部署运行你感兴趣的模型镜像

做leetcode题目的时候get到一个小知识点~

来自collections模块,主要用来跟踪值出现的次数

比如

>>>from collections import Counter
>>>str="aaabbbcccc"
>>>dict=Counter(str)
>>> dict
Counter({'c': 4, 'a': 3, 'b': 3})
>>> dict["c"]
4
>>>dict["d"]
0



您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

TF-IDF(Term Frequency-Inverse Document Frequency)是一种用于信息检索和文本挖掘的常用加权技术。它可以用来评估一个单词对于一个文档集或一个语料库中的某个文档的重要程度。 下面是Python实现TF-IDF算法的示例代码: ```python import math from collections import Counter def tf(word, doc): return doc.count(word) / len(doc) def n_containing(word, doclist): return sum(1 for doc in doclist if word in doc) def idf(word, doclist): return math.log(len(doclist) / (1 + n_containing(word, doclist))) def tfidf(word, doc, doclist): return tf(word, doc) * idf(word, doclist) doclist = ['This is a sample document.', 'Another sample document.', 'And a third one.', 'Is this the first document?'] all_words = [] for doc in doclist: all_words += doc.lower().split() word_count = Counter(all_words) for word in word_count: word_count[word] = word_count[word] / float(len(all_words)) unique_words = set(all_words) tfidf_dict = {} for word in unique_words: tfidf_dict[word] = tfidf(word, doclist[0], doclist) for word in sorted(tfidf_dict, key=tfidf_dict.get, reverse=True): print(word, tfidf_dict[word]) ``` 首先,我们定义了四个函数: - `tf(word, doc)`:计算单词在文档中的出现频率。 - `n_containing(word, doclist)`:计算包含指定单词的文档数量。 - `idf(word, doclist)`:计算指定单词的逆文档频率。 - `tfidf(word, doc, doclist)`:计算指定单词在文档中的TF-IDF值。 然后,我们定义了一个包含多个文档的列表和一个包含所有单词的列表。这使用了Python的`collections`库中的`Counter`函数来计算单词出现的次数,并将其除以单词总数得到每个单词的频率。 接下来,我们计算每个单词的TF-IDF值,并将其存储在一个字典中。最后,我们按照TF-IDF值进行排序,并输出结果。 注意,这的示例代码是使用Python的基本数据结构实现的,实际应用中可能需要使用更高效的数据结构和算法来处理大规模数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值