python计算字符串中字符出现字数,word_counts.most_common() 函数使用方法

本文详细解析了Python中collections模块的Counter类及其most_common()函数的使用方法,展示了如何统计字符串中各字符出现频率并按频次排序,适用于初学者及需要字符串统计的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


# 注意Counter() 输入的是字符串 返回的是用于计算字符串中字符出现的接口

word_counts.most_common() 输入整数时C 返回的是排名前C个的数据  不输入是按照出现次数对所有数据排序

 

word_counts.most_common()   返回值的类型是list[]   第一个参数:字符   第二个参数是:字符出现的次数

 

[x[0] for x in word_counts.most_common()]的作用就是将word_counts.most_common() 返回值的第一个参数x[0]赋值给 vocabulary_inv 

from collections import Counter

str_var = '不管你爱不爱深度学习 反正我爱'

word_counts = Counter(str_var)

#每次都把都把word_counts.most_common()中的汉字  返回给vocabulary_inv
vocabulary_inv = [x[0] for x in word_counts.most_common()]
print("vocabulary_inv和类型",vocabulary_inv, type(vocabulary_inv))


my_vocabulary_inv = []
for x in word_counts.most_common():
    my_vocabulary_inv.append(x[0])
print("my_vocabulary_inv",my_vocabulary_inv)


vocabulary_inv_three = [x[0] for x in word_counts.most_common(3)]
print("vocabulary_inv_three", vocabulary_inv_three)
def get_nlp(): if not hasattr(get_nlp, "nlp"): get_nlp.nlp = spacy.load("en_core_web_sm", disable=["parser", "ner"]) return get_nlp.nlp # 数据处理函数 def batch_clean_text(batch): clean_texts = [] for text in batch['text']: # 数据清洗 text = re.sub(r'<[^>]+>', '', text) # 移除html标签 text = re.sub(r'[^a-zA-Z0-9\s.,!?]', '', text) # 删除特殊符号(保留字母数字和基本标点) text = re.sub(r'\s+', ' ', text) # 合并多余空格 clean_texts.append(text.strip()) # 必须显式收集结果 # 处理停用词函数 # 分词 + 停用词过滤 + 词形还原 nlp = get_nlp() processed_tokens = [] for doc in nlp.pipe(clean_texts, batch_size=100): tokens = [ token.lemma_.lower() # 词形还原并转小写 for token in doc if not token.is_stop # 过滤停用词 and not token.is_punct # 过滤标点 and not token.is_space # 过滤空格 and len(token.lemma_) > 1 # 过滤单字符 ] processed_tokens.append(" ".join(tokens)) # 拼接为字符串 return {"text": processed_tokens} if __name__ == "__main__": # 指定加载路径 dataset = load_dataset( "../data/stanfordnlp___imdb", ) train_data = dataset['train'] # 获取训练集 test_data = dataset['test'] # 测试集 # 应用清洗并保存 train_data = train_data.map( batch_clean_text, batched=True, batch_size=200, num_proc=8, remove_columns=["text"] ) # train_data = train_data.dropna(subset=['text']) # train_data = train_data.dropna(subset=['label']) # # spacy分词过程 # tqdm.pandas(desc="Spacy处理进度") # 删除空行 # train_data = train_data[train_data['processed_tokens'].apply(len) > 0] train_data.save_to_disk("../data/processed_imdb") train_data = pd.DataFrame(dataset['train']) test_data = pd.DataFrame(dataset['test']) # 标签分布可视化 plt.figure(figsize=(8, 5)) train_data['label'].value_counts().plot.pie(autopct='%1.1f%%') plt.title('Class Distribution') plt.show() # 文本长度分析 text_lengths = train_data['text'].apply(lambda x: len(x.split())) plt.figure(figsize=(10,6)) plt.hist(text_lengths, bins=50, range=[0, 1000]) plt.xlabel('Text Length (words)') plt.ylabel('Frequency') plt.title('Text Length Distribution') plt.show() # 高频词统计(示例) from collections import Counter from wordcloud import WordCloud all_text = ' '.join(train_data['text']) words = all_text.split() # 取前1000条加速计算 word_freq = Counter(words) # top20 = word_freq.most_common(20) # 查看前20高频词 # top20 = dict(word_freq.most_common(20)) wordcloud = WordCloud( width=1200, height=600, background_color='white', collocations=False, # 禁用词组组合 max_words=50, # 限制显示词数 contour_width=1 # 添加轮廓线 ).generate_from_frequencies(word_freq) plt.figure(figsize=(14, 7)) plt.imshow(wordcloud) plt.axis('off') plt.title("IMDB Review Keywords", pad=20) plt.show() 代码如上,现在的问题是,词云部分显示数据处理前后词云没有变化,是什么原因导致的,数据处理函数失败了吗
最新发布
04-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值