python jieba分词并统计词频后输出结果到Excel和txt文档方法
作者:体贴的古琴 时间:2023-10-28 21:16:37
前两天,班上同学写论文,需要将很多篇论文题目按照中文的习惯分词并统计每个词出现的频率。
让我帮她实现这个功能,我在网上查了之后发现jieba这个库还挺不错的。
运行环境:
安装python2.7.13:https://www.python.org/downloads/release/python-2713/
安装jieba:pip install jieba
安装xlwt:pip install xlwt
具体代码如下:
#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import jieba
import jieba.analyse
import xlwt #写入Excel表的库
if __name__=="__main__":
wbk = xlwt.Workbook(encoding = 'ascii')
sheet = wbk.add_sheet("wordCount")#Excel单元格名字
word_lst = []
key_list=[]
for line in open('1.txt'):#1.txt是需要分词统计的文档
item = line.strip('\n\r').split('\t') #制表格切分
# print item
tags = jieba.analyse.extract_tags(item[0]) #jieba分词
for t in tags:
word_lst.append(t)
word_dict= {}
with open("wordCount.txt",'w') as wf2: #打开文件
for item in word_lst:
if item not in word_dict: #统计数量
word_dict[item] = 1
else:
word_dict[item] += 1
orderList=list(word_dict.values())
orderList.sort(reverse=True)
# print orderList
for i in range(len(orderList)):
for key in word_dict:
if word_dict[key]==orderList[i]:
wf2.write(key+' '+str(word_dict[key])+'\n') #写入txt文档
key_list.append(key)
word_dict[key]=0
for i in range(len(key_list)):
sheet.write(i, 1, label = orderList[i])
sheet.write(i, 0, label = key_list[i])
wbk.save('wordCount.xls') #保存为 wordCount.xls文件
1.txt是你需要分词统计的文本内容,最后会生成wordCount.txt和wordCount.xls两个文件。下图是最后结果
来源:http://blog.csdn.net/u014070086/article/details/73201590
标签:python,jieba,分词
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
用server.transfer隐藏网页真实地址
2007-12-04 13:02:00
![](https://img.aspxhome.com/file/UploadPic/up/2007120418262385.gif)
Java基于正则表达式实现的替换匹配文本功能【经典实例】
2023-03-15 22:27:44
![](https://img.aspxhome.com/file/2023/7/73047_0s.jpg)
Python super()函数使用及多重继承
2022-10-06 19:21:37
python读取各种文件数据方法解析
2021-08-31 09:16:54
![](https://img.aspxhome.com/file/2023/7/121527_0s.jpg)
浅析Python的命名空间与作用域
2022-11-27 04:19:04
Python多线程实例教程
2022-11-30 14:15:43
利用go-zero在Go中快速实现JWT认证的步骤详解
2024-05-28 15:22:20
用python实现将数组元素按从小到大的顺序排列方法
2022-01-07 22:03:25
PHP取余函数介绍MOD(x,y)与x%y
2023-10-02 20:15:55
python中的字符串切割 maxsplit
2022-04-16 14:35:35
python 追踪except信息方式
2022-10-07 13:46:02
迎来2009年CSS裸奔节(CSS Naked Day )
2009-04-24 12:41:00
![](https://img.aspxhome.com/file/UploadPic/20094/24/qqqqqqqqq-36s.gif)
Python利用matplotlib.pyplot绘图时如何设置坐标轴刻度
2023-09-18 23:32:01
![](https://img.aspxhome.com/file/2023/5/62895_0s.png)
如何利用Python动态模拟太阳系运转
2022-01-14 15:01:43
![](https://img.aspxhome.com/file/2023/3/86313_0s.png)
在Django model中设置多个字段联合唯一约束的实例
2021-02-09 22:04:59
IE 下 href 的 BUG
2008-11-10 12:32:00
.Net Core下使用Dapper的方法
2023-07-16 17:19:17
在Python3中使用asyncio库进行快速数据抓取的教程
2022-04-10 06:41:44
python selenium在打开的浏览器中动态调整User Agent
2022-09-26 13:41:59
![](https://img.aspxhome.com/file/2023/8/133308_0s.png)
Python详解复杂CSV文件处理方法
2021-04-05 11:12:02
![](https://img.aspxhome.com/file/2023/6/67936_0s.png)