用python实现文件的词频统计

"""
@name : 词频统计
@author : huangshilong
@projectname : file_opreat
"""
def deal_text():# 用上下文管理器打开文件with open('Walden.txt','r+') as fp:# 读取文件内容text = fp.read()# 消除大小写text=text.lower()# 消除特殊字符# sub_post = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])", ' ', post)for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_{|}.~’‘':text = text.replace(ch, "")# 将文本分割成单个单词text = text.split()# 返回文本列表return  text
def count_text():# 调用处理文本的函数txt = deal_text()# 创建一个单词字典word_dict ={}# 写入单词元素及出现次数for item in txt:if item not in word_dict:word_dict[item] = 1else:word_dict[item]+=1#得到出现次数前十的一个列表list_top10_word =[]for item in word_dict:list_top10_word.append(word_dict[item])# 通过列表的sort方法对列表进行排序,方便取最后的出现次数最多的十个元素list_top10_word.sort()list_top10_word=list_top10_word[-1:-11:-1]# 使用字典生成式生成次数前十的单词的字典,并输出dict_top10_word = {key:word_dict[key] for key in word_dict if word_dict[key] in list_top10_word}print(dict_top10_word)
count_text()

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部