xiaoyangyang0 2019-05-29
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()