python统计文章单词次数

本文介绍了一种通过Python脚本来统计指定目录下所有英文日记文本文件中最重要的单词的方法。该方法利用了collections模块中的Counter类来计数单词,并且排除了一些常见的连词、介词和谓语动词。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目是这样的:你有一个目录,放了你一个月的日记,都是 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)

学习笔记:
1、collections模块,是python内建的模块,提供了许多有用的集合类。我们这里用到了Counter类和其中的most_common()方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值