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中的TCP及UDP(详解)
Nov 06 Python
python读取目录下最新的文件夹方法
Dec 24 Python
python爬虫爬取微博评论案例详解
Mar 27 Python
解决python tkinter界面卡死的问题
Jul 17 Python
Python代码实现http/https代理服务器的脚本
Aug 12 Python
python 哈希表实现简单python字典代码实例
Sep 27 Python
Python基础之变量基本用法与进阶详解
Jan 03 Python
pytorch 实现查看网络中的参数
Jan 06 Python
Python sql注入 过滤字符串的非法字符实例
Apr 03 Python
使用keras实现BiLSTM+CNN+CRF文字标记NER
Jun 29 Python
python+pytest接口自动化之token关联登录的实现
Apr 06 Python
Elasticsearch 聚合查询和排序
Apr 19 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的宝库目录--PEAR
2006/10/09 PHP
浅析ThinkPHP中execute和query方法的区别
2014/06/13 PHP
Yii2框架BootStrap样式的深入理解
2016/11/07 PHP
PHP设计模式之工厂模式定义与用法详解
2018/04/03 PHP
Input 特殊事件onpopertychange和oninput
2009/06/17 Javascript
Javascript表达式中连续的 && 和 || 之赋值区别
2010/10/17 Javascript
javascript分页代码(当前页码居中)
2012/09/20 Javascript
js设置cookie过期及清除浏览器对应名称的cookie
2013/10/24 Javascript
jQuery基础知识小结
2014/12/22 Javascript
《JavaScript DOM 编程艺术》读书笔记之JavaScript 简史
2015/01/09 Javascript
JavaScript通过使用onerror设置默认图像显示代替alt
2016/03/01 Javascript
全面解析JS字符串和正则表达式中的match、replace、exec等函数
2016/07/01 Javascript
详解如何使用PM2将Node.js的集群变得更加容易
2017/11/15 Javascript
layui-select动态选中值的例子
2019/09/23 Javascript
详解Nuxt内导航栏的两种实现方式
2020/04/16 Javascript
深入解析Python中的变量和赋值运算符
2015/10/12 Python
对比Python中__getattr__和 __getattribute__获取属性的用法
2016/06/21 Python
Python 绘图和可视化详细介绍
2017/02/11 Python
python实现根据指定字符截取对应的行的内容方法
2018/10/23 Python
Python高级特性与几种函数的讲解
2019/03/08 Python
Pandas操作CSV文件的读写实现方法
2019/11/13 Python
Python数据存储之 h5py详解
2019/12/26 Python
pytorch之ImageFolder使用详解
2020/01/06 Python
用Python绘制漫步图实例讲解
2020/02/26 Python
Jupyter notebook 远程配置及SSL加密教程
2020/04/14 Python
聊聊python中的异常嵌套
2020/09/01 Python
加拿大建筑和装修专家:Reno-Depot
2017/12/21 全球购物
Under Armour瑞典官方网站:美国高端运动科技品牌
2018/11/21 全球购物
集体婚礼证婚词
2014/01/13 职场文书
打架检讨书400字
2014/01/17 职场文书
护理专业自我评价
2015/03/11 职场文书
2015年教研员工作总结
2015/05/26 职场文书
会计专业2019暑假实习报告
2019/06/21 职场文书
Golang 正则匹配效率详解
2021/04/25 Golang
解决Redis启动警告问题
2022/02/24 Redis
Java时间工具类Date的常用处理方法
2022/05/25 Java/Android