用python统计单词出现频率
用python的字典数据结构可以很方便地用来统计一篇文章的每个单词出现的频率。在文本相似度计算中,就经常需要用到一个单词在文章中的出现频率,进而可以根据两篇文章共有单词在相应文章中的频率比较,来计算相似度。python的强大功能在很大程度上依赖于字典这种数据结构。字典是一种可变的数据结构,和列表相似。它是一种基于key=>value的数据结构,value值可变,但key是不可变变量,value可以是任何一种数据对象,可以是字符串、整数、列表以及字典。
Code:
def add_words(word,words_dict): """把单词添加到words_dict字典里,并计数""" if word in words_dict: words_dict[word]+=1 else: words_dict[word]=1 import string def process_line(line,words_dict): """处理文件每行数据""" line=line.strip() words_list=line.split() for word in words_list: word=word.lower().strip(string.punctuation) #删除进过分割的单词的尾部的一些符号 add_words(word,words_dict) #调用add_words函数,把单词插入到words_dict字典中 def print_result(words_dict): """按格式输出words_dict中的数据""" val_key_list=[] for key,val in words_dict.items(): val_key_list.append((val,key)) val_key_list.sort(reverse=True) #对val值进行逆排序 print "%-10s%-10s" %("word","count") print "_"*25 for val,key in val_key_list: print "%-12s %3d" %(key,val) ################################################## def main(): """主函数""" words_dict={} pFile=open("speech.txt","r") for line in pFile: process_line(line,words_dict) print "the length of the dictionary:",len(words_dict) print_result(words_dict)
运行结果图(点击查看大图):
还可以对代码进一步处理,让最后结果只输出频率大于2以及单词长度大于3的单词,在一些应用场景中,我们最后需要的只是那些高频词汇以及一些关键词,像“in","is","a"之类的单词实际上没有意义。
Code:
def add_words(word,words_dict): """把单词添加到words_dict字典里,并计数""" if word in words_dict: words_dict[word]+=1 else: words_dict[word]=1 import string def process_line(line,words_dict): """处理文件每行数据""" line=line.strip() words_list=line.split() for word in words_list: word=word.lower().strip(string.punctuation) #删除进过分割的单词的尾部的一些符号 add_words(word,words_dict) #调用add_words函数,把单词插入到words_dict字典中 def print_result(words_dict): """按格式输出words_dict中的数据""" val_key_list=[] for key,val in words_dict.items(): if len(key)>3 and val>2: #过滤结果,只输出词频大于2以及单词长度大于3的单词 val_key_list.append((val,key)) val_key_list.sort(reverse=True) #对val值进行逆排序 print "%-10s%-10s" %("word","count") print "_"*25 for val,key in val_key_list: print "%-12s %3d" %(key,val) ################################################## def main(): """主函数""" words_dict={} pFile=open("speech.txt","r") for line in pFile: process_line(line,words_dict) print "the length of the dictionary:",len(words_dict) print_result(words_dict)
- 用python统计文章单词数
- 一个简单数据挖掘程序