python TF-IDF算法实现文本关键词提取


Posted in Python onMay 29, 2019

TF(Term Frequency)词频,在文章中出现次数最多的词,然而文章中出现次数较多的词并不一定就是关键词,比如常见的对文章本身并没有多大意义的停用词。所以我们需要一个重要性调整系数来衡量一个词是不是常见词。该权重为IDF(Inverse Document Frequency)逆文档频率,它的大小与一个词的常见程度成反比。在我们得到词频(TF)和逆文档频率(IDF)以后,将两个值相乘,即可得到一个词的TF-IDF值,某个词对文章的重要性越高,其TF-IDF值就越大,所以排在最前面的几个词就是文章的关键词。

TF-IDF算法的优点是简单快速,结果比较符合实际情况,但是单纯以“词频”衡量一个词的重要性,不够全面,有时候重要的词可能出现的次数并不多,而且这种算法无法体现词的位置信息,出现位置靠前的词和出现位置靠后的词,都被视为同样重要,是不合理的。

TF-IDF算法步骤:

(1)、计算词频:

词频 = 某个词在文章中出现的次数

考虑到文章有长短之分,考虑到不同文章之间的比较,将词频进行标准化

词频 = 某个词在文章中出现的次数/文章的总词数

词频 = 某个词在文章中出现的次数/该文出现次数最多的词出现的次数

(2)、计算逆文档频率

需要一个语料库(corpus)来模拟语言的使用环境。

逆文档频率 = log(语料库的文档总数/(包含该词的文档数 + 1))

(3)、计算TF-IDF

TF-IDF = 词频(TF)* 逆文档频率(IDF)

详细代码如下:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
 
'''
计算文档的TF-IDF
'''
import codecs
import os
import math
import shutil
 
#读取文本文件
def readtxt(path):
 with codecs.open(path,"r",encoding="utf-8") as f:
  content = f.read().strip()
 return content
 
#统计词频
def count_word(content):
 word_dic ={}
 words_list = content.split("/")
 del_word = ["\r\n","/s"," ","/n"]
 for word in words_list:
  if word not in del_word:
   if word in word_dic:
    word_dic[word] = word_dic[word]+1
   else:
    word_dic[word] = 1
 return word_dic
 
#遍历文件夹
def funfolder(path):
 filesArray = []
 for root,dirs,files in os.walk(path):
  for file in files:
   each_file = str(root+"//"+file)
   filesArray.append(each_file)
 return filesArray
 
 
#计算TF-IDF
def count_tfidf(word_dic,words_dic,files_Array):
 word_idf={}
 word_tfidf = {}
 num_files = len(files_Array)
 for word in word_dic:
  for words in words_dic:
   if word in words:
    if word in word_idf:
     word_idf[word] = word_idf[word] + 1
    else:
     word_idf[word] = 1
 for key,value in word_dic.items():
  if key !=" ":
   word_tfidf[key] = value * math.log(num_files/(word_idf[key]+1))
 
 #降序排序
 values_list = sorted(word_tfidf.items(),key = lambda item:item[1],reverse=True)
 return values_list
 
#新建文件夹
def buildfolder(path):
 if os.path.exists(path):
  shutil.rmtree(path)
 os.makedirs(path)
 print("成功创建文件夹!")
 
#写入文件
def out_file(path,content_list):
 with codecs.open(path,"a",encoding="utf-8") as f:
  for content in content_list:
   f.write(str(content[0]) + ":" + str(content[1])+"\r\n")
 print("well done!")
 
def main():
 #遍历文件夹
 folder_path = r"分词结果"
 files_array = funfolder(folder_path)
 #生成语料库
 files_dic = []
 for file_path in files_array:
  file = readtxt(file_path)
  word_dic = count_word(file)
  files_dic.append(word_dic)
 #新建文件夹
 new_folder = r"tfidf计算结果"
 buildfolder(new_folder)
 
 #计算tf-idf,并将结果存入txt
 i=0
 for file in files_dic:
  tf_idf = count_tfidf(file,files_dic,files_array)
  files_path = files_array[i].split("//")
  #print(files_path)
  outfile_name = files_path[1]
  #print(outfile_name)
  out_path = r"%s//%s_tfidf.txt"%(new_folder,outfile_name)
  out_file(out_path,tf_idf)
  i=i+1
 
if __name__ == '__main__':
 main()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python调用java的Webservice示例
Mar 10 Python
MySQLdb ImportError: libmysqlclient.so.18解决方法
Aug 21 Python
Python警察与小偷的实现之一客户端与服务端通信实例
Oct 09 Python
Python实现简单的可逆加密程序实例
Mar 05 Python
利用Python获取操作系统信息实例
Sep 02 Python
python anaconda 安装 环境变量 升级 以及特殊库安装的方法
Jun 21 Python
Python中常用信号signal类型实例
Jan 25 Python
解决seaborn在pycharm中绘图不出图的问题
May 24 Python
Python类中方法getitem和getattr详解
Aug 30 Python
Python list与NumPy array 区分详解
Nov 06 Python
python中的subprocess.Popen()使用详解
Dec 25 Python
pytorch实现线性回归以及多元回归
Apr 11 Python
详解Python odoo中嵌入html简单的分页功能
May 29 #Python
Python 3.8中实现functools.cached_property功能
May 29 #Python
Python3+Pycharm+PyQt5环境搭建步骤图文详解
May 29 #Python
Python安装与基本数据类型教程详解
May 29 #Python
python登录WeChat 实现自动回复实例详解
May 28 #Python
Python语言进阶知识点总结
May 28 #Python
python图像和办公文档处理总结
May 28 #Python
You might like
PHP EOT定界符的使用详解
2008/09/30 PHP
php fckeditor 调用的函数
2009/06/21 PHP
基于preg_match_all采集后数据处理的一点心得笔记(编码转换和正则匹配)
2014/01/31 PHP
php相对当前文件include其它文件的方法
2015/03/13 PHP
php强制下载文件函数
2016/08/24 PHP
PHP的mysqli_stmt_init()函数讲解
2019/01/24 PHP
IE autocomplete internet explorer's autocomplete
2007/06/30 Javascript
JavaScript 快捷键设置实现代码
2009/03/13 Javascript
js 时间函数应用加、减、比较、格式转换的示例代码
2013/08/23 Javascript
JS如何将数字类型转化为没3个一个逗号的金钱格式
2014/01/27 Javascript
Javscript删除数组中指定元素并返回新数组
2014/03/06 Javascript
Javascript中的五种数据类型详解
2014/12/26 Javascript
javascript中mouseover、mouseout使用详解
2015/07/19 Javascript
nodejs利用ajax实现网页无刷新上传图片实例代码
2017/06/06 NodeJs
JS实现仿UC浏览器前进后退效果的实例代码
2017/07/17 Javascript
BootStrap数据表格实例代码
2017/09/13 Javascript
js实现点击上传图片并设为模糊背景
2020/08/02 Javascript
vue 解决mintui弹窗弹起来,底部页面滚动bug问题
2020/11/12 Javascript
基于JavaScript实现随机点名器
2021/02/25 Javascript
python服务器与android客户端socket通信实例
2014/11/12 Python
Python时间和字符串转换操作实例分析
2019/03/16 Python
Django 迁移、操作数据库的方法
2019/08/02 Python
Python concurrent.futures模块使用实例
2019/12/24 Python
python获取本周、上周、本月、上月及本季的时间代码实例
2020/09/08 Python
用HTML5制作视频拼图的教程
2015/05/13 HTML / CSS
英国二手iPhone、音乐、电影和游戏商店:musicMagpie
2018/10/26 全球购物
三星法国官方网站:Samsung法国
2019/10/31 全球购物
高一历史教学反思
2014/01/13 职场文书
新学期家长寄语
2014/01/19 职场文书
表演方阵解说词
2014/02/08 职场文书
三分钟演讲稿事例
2014/03/03 职场文书
2014全国两会学习心得体会1000字
2014/03/10 职场文书
golang中的空slice案例
2021/04/27 Golang
用Python爬取某乎手机APP数据
2021/06/15 Python
实例详解Python的进程,线程和协程
2022/03/13 Python
springboot读取nacos配置文件
2022/05/20 Java/Android