python jieba分词并统计词频后输出结果到Excel和txt文档方法

yipeiwu_com7年前Python基础

前两天,班上同学写论文,需要将很多篇论文题目按照中文的习惯分词并统计每个词出现的频率。

让我帮她实现这个功能,我在网上查了之后发现jieba这个库还挺不错的。

运行环境:

  1. 安装python2.7.13:https://www.python.org/downloads/release/python-2713/
  2. 安装jieba:pip install jieba
  3. 安装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两个文件。下图是最后结果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python获取文件ssdeep值的方法

本文实例讲述了Python获取文件ssdeep值的方法,分享给大家供大家参考。具体方法如下: 首先,得到ssdeep值,需要先import ssdeep 在ubuntu上安装pyssde...

python使用PyGame播放Midi和Mp3文件的方法

本文实例讲述了python使用PyGame播放Midi和Mp3文件的方法。分享给大家供大家参考。具体实现方法如下: ''' pg_midi_sound101.py play midi...

用Python写一个模拟qq聊天小程序的代码实例

Python 超简单的聊天程序 客户端: import socket, sys host = '10.248.27.23' # host = raw_input("Plz imput...

Python unittest模块用法实例分析

本文实例讲述了Python unittest模块用法。分享给大家供大家参考,具体如下: python的unittest模块提供了一个测试框架,只要我们写一个继承unittest.Test...

Python可变参数函数用法实例

本文实例讲述了Python可变参数函数用法。分享给大家供大家参考。具体如下: #!/usr/bin/python def f1(a,b): print a,b def f2(a,*b...