文章来自于我的个人博客: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值并排序的更多相关文章

  1. 用Python做SVD文档聚类---奇异值分解----文档相似性----LSI(潜在语义分析)

    转载请注明出处:电子科技大学EClab——落叶花开http://www.cnblogs.com/nlp-yekai/p/3848528.html SVD,即奇异值分解,在自然语言处理中,用来做潜在语义 ...

  2. Python处理Excel文档(xlrd, xlwt, xlutils)

    简介 xlrd,xlwt和xlutils是用Python处理Excel文档(*.xls)的高效率工具.其中,xlrd只能读取xls,xlwt只能新建xls(不可以修改),xlutils能将xlrd.B ...

  3. python+selenium自动化软件测试(第12章):Python读写XML文档

    XML 即可扩展标记语言,它可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语言进 行定义的源语言.xml 有如下特征: 首先,它是有标签对组成:<aa></aa> ...

  4. 【转】Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)

    [转]Python之xml文档及配置文件处理(ElementTree模块.ConfigParser模块) 本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 ...

  5. 获取文档版本版本值 滚动标识符 游标 控制查询如何执行 控制查询在哪些分片执行 boost加权

    映射mapping.json{ "book": { "_index": { "enabled": true }, "_id&quo ...

  6. 使用Python操作Excel文档(一)

    Python | 使用Python操作Excel文档(一) 0 前言 在阅读本文之前,请确保您已满足或可能满足以下条件: 请确保您具备基本的Python编程能力. 请确保您会使用Excel. 请确保您 ...

  7. 使用Python从Markdown文档中自动生成标题导航

    概述 知识与思路 代码实现 概述 Markdown 很适合于技术写作,因为技术写作并不需要花哨的排版和内容, 只要内容生动而严谨,文笔朴实而优美. 为了编写对读者更友好的文章,有必要生成文章的标题导航 ...

  8. Openstack python api 学习文档 api创建虚拟机

    Openstack python api 学习文档 转载请注明http://www.cnblogs.com/juandx/p/4953191.html 因为需要学习使用api接口调用openstack ...

  9. [转载]linux+nginx+python+mysql安装文档

    原文地址:linux+nginx+python+mysql安装文档作者:oracletom # 开发包(如果centos没有安装数据库服务,那么要安装下面的mysql开发包) MySQL-devel- ...

随机推荐

  1. Highmaps网页图表教程之Highmaps第一个实例与图表构成

    Highmaps网页图表教程之Highmaps第一个实例与图表构成 Highmaps第一个实例 下面我们来实现本教程的第一个Highmaps实例. [实例1-1:hellomap]下面来制作一个中国地 ...

  2. python 并集union, 交集intersection, 差集difference, 对称差集symmetric_difference

    python的集合set和其他语言类似,是一个无序不重复元素集, 可用于消除重复元素. 支持union(联合), intersection(交), difference(差)和sysmmetric d ...

  3. 机器学习之路: python 实践 提升树 XGBoost 分类器

    git: https://github.com/linyi0604/MachineLearning 数据集被我下载到本地,可以去我的git上拿数据集 XGBoost提升分类器 属于集成学习模型 把成百 ...

  4. 拉格朗日乘子法以及KKT条件

    拉格朗日乘子法是一种优化算法,主要用来解决约束优化问题.他的主要思想是通过引入拉格朗日乘子来将含有n个变量和k个约束条件的约束优化问题转化为含有n+k个变量的无约束优化问题. 其中,利用拉格朗日乘子法 ...

  5. 常用SQL脚本记录一

    20.SUM()和 列+ 统计结果时:如果列里有一行为null,SUM函数会忽略它:如果+,则结果集也为NULL了 19 SUBSTRING (expression,startIndex, endIn ...

  6. 【POJ】1486:Sorting Slides【二分图关键边判定】

    Sorting Slides Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 5390   Accepted: 2095 De ...

  7. bzoj 5055: 膜法师 -- 树状数组

    5055: 膜法师 Time Limit: 10 Sec  Memory Limit: 128 MB Description 在经历过1e9次大型战争后的宇宙中现在还剩下n个完美维度, 现在来自多元宇 ...

  8. OpenGL和GLSL版本更迭

    前言 最近才发现,自己写的glsl和教程的glsl版本对不上,一直以为是xcode不允许使用太高版本,只能使用OpenGL 2.0的版本,却不知使用glfw可以使用到最新的OpenGL版本.

  9. Codeforces Round #353 (Div. 2) E. Trains and Statistic dp 贪心

    E. Trains and Statistic 题目连接: http://www.codeforces.com/contest/675/problem/E Description Vasya comm ...

  10. Set常用子类特点

    HashSet:       重写   hashCode和equals方法                                        特点:无序,唯一      底层结构是:    ...