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- ...
随机推荐
- count 【mysql】
如果你的需要是统计总行数时,为什么要使用count(*),而避免使用指定具体的列名? count()函数里面的参数是列名的的时候,那么会计算这个字段有值项的次数.也就是,该字段没有值的项并不会进入计算 ...
- NetCore+Dapper WebApi架构搭建(五):Swagger构建WebApi界面
上一节讲解了仓储的依赖注入,想必现在都可以通过构造函数依赖注入直接调用 但是WebApi只是提供一个接口调用,为了方便我们的操作,我们得给他加上一个图形化界面工具,使用Swagger WebApi项目 ...
- Android调用C#的WebService
Android调用C#写的WebService 学习自: http://www.cnblogs.com/kissazi2/p/3406662.html 运行环境 Win10 VS 2015 Andro ...
- Python学习笔记(六)—元组的操作
元祖也是一个列表,它和list的区别是元祖里面的元素无法修改: 如果元祖里面只有一个元素的话,那么你必须在这个元素后边加上逗号,这样才是元祖的类型:否则类型会显示其他类型 元组的定义: 元祖中的方法: ...
- Loadrunner问题:Monitor name :Windows Resources. Cannot create measurement Processor|% Processor Time|_Total on machine 192.168.0.1
说明: 在Loadrunner监控windows系统资源的时候,在添加好windows Resources后运行发现报如下错误: int: Check that there is such a mea ...
- [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See https://www.chromestatus.com/features/5093566007214080
相信如果用谷歌浏览器做移动端页面的时候 用touch事件的时候应该遇到过这个东东吧 documet.addEventListener("touchstart",function() ...
- The YubiKey -- COMPARISON OF VERSIONS
COMPARISON OF YUBIKEY VERSIONS BASICSTANDARD & NANO BASICEDGE & EDGE-N PREMIUMNEO & NE ...
- The YubiKey -- HOW IT WORKS
A single YubiKey has multiple functions for protecting access to your email, your apps and your phys ...
- golang 实现轻量web框架
经常看到很多同学在打算使用go做开发的时候会问用什么http框架比较好.其实go的 http package 非常强大,对于一般的 http rest api 开发,完全可以不用框架就可以实现想要的功 ...
- Apple Developer Registration and DUNS Number Not Accepted
Now that I have my Mac and app source code. I’m ready to start working on my first app. The next ste ...