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

时间:2023-03-08 17:10:11
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