Python统计英文日记高频词并过滤停用词的实现方法
本文介绍使用Python统计英文日记中高频单词的方法。通过collections模块的Counter类统计词频,并利用正则表达式提取单词。核心逻辑在于过滤常见停用词(如冠词、介词),通过迭代查找第一个非停用词作为最重要词汇,完整展示代码实现与相关工具推荐。
Python统计英文日记高频词并过滤停用词的实现方法
本文详细介绍使用Python实现统计文章单词出现次数的功能示例,供读者参考学习。
具体需求如下:假设存在一个包含一个月日记文件的目录,所有文件均为txt格式。为简化处理,假设内容均为英文,请编写程序统计出每篇日记中出现频率最高且最具代表性的单词。
该任务本质是统计文章中出现次数最多的单词,但需要排除常见的连词、介词和谓语动词等无实际意义的词汇。具体实现代码如下:
#coding=utf-8
import collections
import re
import os
useless_words=('the','a','an','and','by','of','in','on','is','to')
def get_important_word(file):
f=open(file)
word_counter=collections.Counter()
for line in f:
words=re.findall('\w+',line.lower())
word_counter.update(words)
f.close()
most_important_word=word_counter.most_common(1)[0][0]
count=2
while(most_important_word in useless_words):
most_important_word=word_counter.most_common(count)[count-1][0]
count+=1
num=word_counter.most_common(count)[count-1][1]
print 'the most important word in %s is %s,it appears %d times'%(file,most_important_word,num)
if __name__=='__main__':
filepath='.'
for dirpath,dirname,dirfiles in os.walk(filepath):
for file in dirfiles:
if os.path.splitext(file)[1]=='.txt':
abspath=os.path.join(dirpath,file)
if os.path.isfile(abspath):
get_important_word(abspath)
关键知识点解析:
代码中使用了collections模块,这是Python内置的标准库,提供了多种有用的集合类。本例主要使用了其中的Counter类以及该类的most_common()方法来进行词频统计和排序。
此外,推荐两款在线统计工具供参考:
在线字数统计工具: http://tools.jb51.net/code/zishutongji
在线字符统计与编辑工具: http://tools.jb51.net/code/char_tongji
如需了解更多Python相关知识,可参考本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》。
希望上述内容能对读者的Python编程实践有所帮助。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













