Python每日一练(1):计算文件夹内各个文章中出现次数最多的单词


#coding:utf-8
import os,re

path = 'test'
files = os.listdir(path)

def count_word(words):
    dic = {}
    max = 0
    marked_key = ''
    #计算每个单词出现的次数
    for word in words:
        if dic.has_key(word) is False:
            dic[word] = 1
        else:
            dic[word] = dic[word] +1
    #每个字典的值之间做比较,得出最大的那个数字
    for key,value in dic.items():
        if dic[key] > max:
            max = dic[key]
            marked_key = key
    #跳出for循环打印出单词和单词出现的次数
    print(marked_key,max)

for f in files:
    with open(os.path.join(path,f)) as diary:
        words = re.findall("[a-zA-Z]+'*-*[a-zA-z]", diary.read())
        count_word(words)

#has_key(key) : 函数用于判断键是否存在于字典中,如果键在字典dict里返回true,否则返回false。这里用于判断字典内的键是否出现过。

 

这个是Git上的Python每日一联小项目,我就不提交到那边了,写到这里来。

项目地址:https://github.com/Yixiaohan/show-me-the-code


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM