用Python统计英文书词频,排除停用词,用openpyxl写进Excel

import re
from openpyxl import Workbook
import warnings
warnings.filterwarnings('ignore')

wb = Workbook()
ws1 = wb.create_sheet('词频统计')
ws1['A1'] = '排序'
ws1['B1'] = '单词'
ws1['C1'] = '词频'
wb.save('./斯宾塞自传词频统计.xlsx')
print("词频工作表创建好啦!")

txt = open('spencer.txt',errors='ignore').read().lower()
txt = re.sub(r'[^a-zA-Z]',' ', txt)
words = txt.split()
print("文本单词处理好啦!")

stop_words = open('stop_words.txt').read()
stop_words = re.sub(r'[^a-zA-Z]',' ', stop_words)
stop_words = stop_words.split()
print("停用词表处理好啦!")


words = [x for x in words if x not in stop_words]
print("已经从文本中排除停用词啦!")

counts = {}
for word in words:
    if word in counts:
        counts[word] = counts[word] + 1
    elif word not in counts:
        counts[word] = 1
print("所有单词的词频计算好啦!")

lst = list(counts.items())
lst.sort(key = lambda k:k[1], reverse = True)
print("词频排序好啦!下面是排序好的词频")

x = 2
i = 0
while i <= 10000:
    word,count = lst[i]
    ws1['A'+str(x)] = i+1
    ws1['B'+str(x)] = word
    ws1['C'+str(x)] = count
    i += 1
    x += 1
print("词频已经全部写入Excel表格啦!")
wb.save('./斯宾塞自传词频统计.xlsx')
wb.close()
print("工作表已经关掉啦!")

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值