python TF-IDF算法实现文本关键词提取
TF(TermFrequency)词频,在文章中出现次数最多的词,然而文章中出现次数较多的词并不一定就是关键词,比如常见的对文章本身并没有多大意义的停用词。所以我们需要一个重要性调整系数来衡量一个词是不是常见词。该权重为IDF(InverseDocumentFrequency)逆文档频率,它的大小与一个词的常见程度成反比。在我们得到词频(TF)和逆文档频率(IDF)以后,将两个值相乘,即可得到一个词的TF-IDF值,某个词对文章的重要性越高,其TF-IDF值就越大,所以排在最前面的几个词就是文章的关键词。
TF-IDF算法的优点是简单快速,结果比较符合实际情况,但是单纯以“词频”衡量一个词的重要性,不够全面,有时候重要的词可能出现的次数并不多,而且这种算法无法体现词的位置信息,出现位置靠前的词和出现位置靠后的词,都被视为同样重要,是不合理的。
TF-IDF算法步骤:
(1)、计算词频:
词频=某个词在文章中出现的次数
考虑到文章有长短之分,考虑到不同文章之间的比较,将词频进行标准化
词频=某个词在文章中出现的次数/文章的总词数
词频=某个词在文章中出现的次数/该文出现次数最多的词出现的次数
(2)、计算逆文档频率
需要一个语料库(corpus)来模拟语言的使用环境。
逆文档频率=log(语料库的文档总数/(包含该词的文档数+1))
(3)、计算TF-IDF
TF-IDF=词频(TF)*逆文档频率(IDF)
详细代码如下:
#!/usr/bin/envpython
#-*-coding:utf-8-*-
'''
计算文档的TF-IDF
'''
importcodecs
importos
importmath
importshutil
#读取文本文件
defreadtxt(path):
withcodecs.open(path,"r",encoding="utf-8")asf:
content=f.read().strip()
returncontent
#统计词频
defcount_word(content):
word_dic={}
words_list=content.split("/")
del_word=["\r\n","/s","","/n"]
forwordinwords_list:
ifwordnotindel_word:
ifwordinword_dic:
word_dic[word]=word_dic[word]+1
else:
word_dic[word]=1
returnword_dic
#遍历文件夹
deffunfolder(path):
filesArray=[]
forroot,dirs,filesinos.walk(path):
forfileinfiles:
each_file=str(root+"//"+file)
filesArray.append(each_file)
returnfilesArray
#计算TF-IDF
defcount_tfidf(word_dic,words_dic,files_Array):
word_idf={}
word_tfidf={}
num_files=len(files_Array)
forwordinword_dic:
forwordsinwords_dic:
ifwordinwords:
ifwordinword_idf:
word_idf[word]=word_idf[word]+1
else:
word_idf[word]=1
forkey,valueinword_dic.items():
ifkey!="":
word_tfidf[key]=value*math.log(num_files/(word_idf[key]+1))
#降序排序
values_list=sorted(word_tfidf.items(),key=lambdaitem:item[1],reverse=True)
returnvalues_list
#新建文件夹
defbuildfolder(path):
ifos.path.exists(path):
shutil.rmtree(path)
os.makedirs(path)
print("成功创建文件夹!")
#写入文件
defout_file(path,content_list):
withcodecs.open(path,"a",encoding="utf-8")asf:
forcontentincontent_list:
f.write(str(content[0])+":"+str(content[1])+"\r\n")
print("welldone!")
defmain():
#遍历文件夹
folder_path=r"分词结果"
files_array=funfolder(folder_path)
#生成语料库
files_dic=[]
forfile_pathinfiles_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
forfileinfiles_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()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。