python 分词计算文档TF-IDF值并排序
文章来自于我的个人博客:python 分词计算文档TF-IDF值并排序
该程序实现的功能是:首先读取一些文档,然后通过jieba来分词,将分词存入文件,然后通过sklearn计算每一个分词文档中的tf-idf值,再将文档排序输入一个大文件里
依赖包:
sklearn
jieba
注:此程序參考了一位同行的程序后进行了改动
# -*- coding: utf-8 -*-
"""
@author: jiangfuqiang
""" import os
import jieba
import jieba.posseg as pseg
import sys
import re
import time
import string
from sklearn import feature_extraction
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
reload(sys) sys.setdefaultencoding('utf-8') def getFileList(path):
filelist = []
files = os.listdir(path)
for f in files:
if f[0] == '.':
pass
else:
filelist.append(f)
return filelist,path def fenci(filename,path,segPath):
f = open(path +"/" + filename,'r+')
file_list = f.read()
f.close() #保存粉刺结果的文件夹 if not os.path.exists(segPath):
os.mkdir(segPath) #对文档进行分词处理
seg_list = jieba.cut(file_list,cut_all=True)
#对空格。换行符进行处理
result = []
for seg in seg_list:
seg = ''.join(seg.split())
reg = 'w+'
r = re.search(reg,seg)
if seg != '' and seg != '
' and seg != ' ' and seg != '=' and
seg != '[' and seg != ']' and seg != '(' and seg != ')' and not r:
result.append(seg) #将分词后的结果用空格隔开,保存至本地
f = open(segPath+"/"+filename+"-seg.txt","w+")
f.write(' '.join(result))
f.close() #读取已经分词好的文档。进行TF-IDF计算
def Tfidf(filelist,sFilePath,path):
corpus = []
for ff in filelist:
fname = path + ff
f = open(fname+"-seg.txt",'r+')
content = f.read()
f.close()
corpus.append(content) vectorizer = CountVectorizer()
transformer = TfidfTransformer()
tfidf = transformer.fit_transform(vectorizer.fit_transform(corpus))
word = vectorizer.get_feature_names() #全部文本的关键字
weight = tfidf.toarray() if not os.path.exists(sFilePath):
os.mkdir(sFilePath) for i in range(len(weight)):
print u'----------writing all the tf-idf in the ',i,u'file into ', sFilePath+'/' +string.zfill(i,5)+".txt"
f = open(sFilePath+"/"+string.zfill(i,5)+".txt",'w+')
for j in range(len(word)):
f.write(word[j] + " " + str(weight[i][j]) + "
")
f.close() if __name__ == "__main__":
#保存tf-idf的计算结果文件夹
sFilePath = "/home/lifeix/soft/allfile/tfidffile"+str(time.time())
#保存分词的文件夹
segPath = '/home/lifeix/soft/allfile/segfile'
(allfile,path) = getFileList('/home/lifeix/soft/allkeyword')
for ff in allfile:
print "Using jieba on " + ff
fenci(ff,path,segPath) Tfidf(allfile,sFilePath,segPath)
#对整个文档进行排序
os.system("sort -nrk 2 " + sFilePath+"/*.txt >" + sFilePath + "/sorted.txt")
python 分词计算文档TF-IDF值并排序的更多相关文章
- 用Python做SVD文档聚类---奇异值分解----文档相似性----LSI(潜在语义分析)
转载请注明出处:电子科技大学EClab——落叶花开http://www.cnblogs.com/nlp-yekai/p/3848528.html SVD,即奇异值分解,在自然语言处理中,用来做潜在语义 ...
- Python处理Excel文档(xlrd, xlwt, xlutils)
简介 xlrd,xlwt和xlutils是用Python处理Excel文档(*.xls)的高效率工具.其中,xlrd只能读取xls,xlwt只能新建xls(不可以修改),xlutils能将xlrd.B ...
- python+selenium自动化软件测试(第12章):Python读写XML文档
XML 即可扩展标记语言,它可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语言进 行定义的源语言.xml 有如下特征: 首先,它是有标签对组成:<aa></aa> ...
- 【转】Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)
[转]Python之xml文档及配置文件处理(ElementTree模块.ConfigParser模块) 本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 ...
- 获取文档版本版本值 滚动标识符 游标 控制查询如何执行 控制查询在哪些分片执行 boost加权
映射mapping.json{ "book": { "_index": { "enabled": true }, "_id&quo ...
- 使用Python操作Excel文档(一)
Python | 使用Python操作Excel文档(一) 0 前言 在阅读本文之前,请确保您已满足或可能满足以下条件: 请确保您具备基本的Python编程能力. 请确保您会使用Excel. 请确保您 ...
- 使用Python从Markdown文档中自动生成标题导航
概述 知识与思路 代码实现 概述 Markdown 很适合于技术写作,因为技术写作并不需要花哨的排版和内容, 只要内容生动而严谨,文笔朴实而优美. 为了编写对读者更友好的文章,有必要生成文章的标题导航 ...
- Openstack python api 学习文档 api创建虚拟机
Openstack python api 学习文档 转载请注明http://www.cnblogs.com/juandx/p/4953191.html 因为需要学习使用api接口调用openstack ...
- [转载]linux+nginx+python+mysql安装文档
原文地址:linux+nginx+python+mysql安装文档作者:oracletom # 开发包(如果centos没有安装数据库服务,那么要安装下面的mysql开发包) MySQL-devel- ...
随机推荐
- [SQL]196. Delete Duplicate Emails
Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique ...
- CSS3组件化之ios版菊花loading
<div class="juhua-loading"> <div class="jh-circle1 jh-circle-ios">&l ...
- 1017 Queueing at Bank (25)(25 point(s))
problem Suppose a bank has K windows open for service. There is a yellow line in front of the window ...
- anaconda安装tensorflow后pip安装jieba出错的问题
安装jieba出错,参考https://www.cnblogs.com/minsons/p/7872647.html TypeError: parse() got an unexpected keyw ...
- Qt Quick快速入门之线程基础
首先必须明确的是,Qt中的线程使用是相对复杂的,并不像C#中那么随意,特别是结合串口.网络编程等,使用时稍有不慎就会出问题,然后Qt里面经常出了问题就直接崩溃(这个真是谁用谁知道),所以如果在功能上用 ...
- [BZOJ5291][BJOI2018]链上二次求和(线段树)
感觉自己做的麻烦了,但常数似乎不算差.(只是Luogu最慢的点不到2s本地要跑10+s) 感觉我的想法是最自然的,但不明白为什么网上似乎找不到这种做法.(不过当然所有的做法都是分类大讨论,而我的方法手 ...
- 2 Spring4 之Bean的配置
Spring4 之Bean的配置 1 IOC & DI 概述 IOC(Inversion of Control):其思想是反转资源获取的方向. 传统的资源查找方式要求组件向容器发起请求查找资源 ...
- hdu 1732 bfs
题意:推箱子游戏 代码写错居然卡内存!! 搞了两天了 #include <iostream> #include <cstdio> #include <cstring> ...
- leetcode659. Split Array into Consecutive Subsequences
leetcode659. Split Array into Consecutive Subsequences 题意: 您将获得按升序排列的整数数组(可能包含重复项),您需要将它们拆分成多个子序列,其中 ...
- SpringMVC 方法参数设置
/** 在方法中配置参数: (1) 内置对象配置: request:获取cookie.请求头... 获取项目根路径 request.getContextPath() response:用于ajax的输 ...