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设计】。

相关文章

Numpy将二维数组添加到空数组的实现

使用append函数将一个二维数组添加到一个空数组,关键是维度要对的上 a=np.empty([0,3]) b = np.array([[1,2,3],[4,5,6]]) c=[[7...

Sanic框架蓝图用法实例分析

本文实例讲述了Sanic框架蓝图用法。分享给大家供大家参考,具体如下: 蓝图是可以用于应用程序内子路由的对象。蓝图并未向应用程序内添加路由,而是定义了用于添加路由的类似方法,然后以灵活且...

python隐藏终端执行cmd命令的方法

在用pyinstaller打包后不想要后面的终端命令框,但是打包时加了-w或者--noconsole命令后会导致cmd程序不能运行从而出错。这个时候用subprocess可以解决该类问题...

深入理解python中sort()与sorted()的区别

Python list内置sort()方法用来排序,也可以用python内置的全局sorted()方法来对可迭代的序列排序生成新的序列 一,最简单的排序 1.使用sort排序 my_...

Python WSGI的深入理解

前言 本文主要介绍的是Python WSGI相关内容,主要来自以下网址: What is WSGI? WSGI Tutorial An Introduction t...