使用Python读取一个文本文件并计算其中每个单词出现的次数

本文展示了如何使用Python中的re模块和matplotlib库对《哈姆雷特》文本进行单词频率分析,提取并可视化了最常见的10个单词及其出现次数。

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

import re
import matplotlib.pyplot as plt
from collections import Counter
word_counts = {}
with open('E:\自然语言处理\Hamlet(2).txt') as f:
    for line in f:
        words = line.strip().lower().split()
        for word in words:
            word = re.sub(r'[^a-zA-Z]+','',word)
            if word in word_counts:
                word_counts[word] += 1
            else:
                word_counts[word] = 1
top_words = Counter(word_counts).most_common(10)
top_words_list = [word[0] for word in top_words]
top_words_counts = [word[1] for word in top_words]
plt.bar(top_words_list, top_words_counts)
plt.xlabel('单词')
plt.ylabel('出现次数')
plt.title('前10个出现次数最多的单词')
plt.xticks(rotation=45)
plt.rcParams['font.sans-serif'] = ['SimHei']  # 指定使用中文字体
for i, count in enumerate(top_words_counts):
    plt.text(i, count, str(count), ha='center', va='bottom')
plt.show()
print(word_counts)

我们假设我们获取了一个哈姆雷特文本,要进行每个单词的统计

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程初学者01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值