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- ...
随机推荐
- 多套方案来提高python web框架的并发处理能力
Python常见部署方法有 : fcgi :用spawn-fcgi或者框架自带的工具对各个project分别生成监听进程,然后和http 服务互动 wsgi :利用http服务的mod_wsgi模 ...
- leetcode 相交链表 python实现
这道题 要想解决其实不难, 开两层循环进行遍历就能实现,但是会超时 如果想要O(n) 的时间复杂度, 我考虑用哈希表来存储遍历过的元素,如果发现当前遍历的元素在哈希表里,那说明交叉点就在这 这里利用了 ...
- poj 3667 线段树
题意:1 a:询问是不是有连续长度为a的空房间,有的话住进最左边2 a b:将[a,a+b-1]的房间清空思路:记录区间中最长的空房间线段树操作:update:区间替换 query:询问满足条件的最左 ...
- [LeetCode] Pacific Atlantic Water Flow 题解
题意 题目 思路 一开始想用双向广搜来做,找他们相碰的点,但是发现对其的理解还是不够完全,导致没写成功.不过,后来想清楚了,之前的错误可能在于从边界点进行BFS,其访问顺序应该是找到下一个比当前那个要 ...
- Codeforces Round #298 (Div. 2) C. Polycarpus' Dice 数学
C. Polycarpus' Dice Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/534/p ...
- CSS选择器复习
通用选择器:* 选择到所有的元素 选择子元素:> 选择到元素的直接后代(第一级子元素) 相邻兄弟选择器:+ 选择到紧随目标元素后的第一个元素 普通兄弟选择器:~ 选择到紧随其后的所有兄弟元素 伪 ...
- 1、安装Redis的PHP扩展
1.安装Redis的PHP扩展 1.1 安装phpize yum install php-devel 1.2 下载扩展源码包,直接用wget #wget下载github上的文件 wget https: ...
- AbstractAction
package cn.tz.action.abs; import java.io.File; import java.io.IOException; import java.text.SimpleDa ...
- js异步任务处理方式
一.es6(es2015)之前:使用原始的callback函数,会陷入回掉地域 this.$http.jsonp('/login', (res) => { this.$http.jsonp('/ ...
- Latest SQLite binary for January 2015
Latest SQLite binary for January 2015 Well I went through quite a few threads to find an updated, de ...