【第 0006 题:你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。】
————————————————————————————————————————————————————————————————————
重要的就是查找与统计
查找:使用【re】模块的findall方法
统计:使用list.Counter() 方法
————————————————————————————————————————————————————
每篇日记的统计可以使用如下代码:
import re
from collections import Counter
import os
wordsdict={}
def wordcount(filename):
with open(filename,'r',encoding='utf-8') as f:
words=f.read().lower()
word='[a-zA-Z]+'
#正则查找单词,返回list
allwords=re.findall(word,words)
#统计个数,返回dict
worddict=Counter(allwords)
return worddict
if __name__ == "__main__":
filepath='g://python//'
#遍历文件夹下的所有文件
for x in os.listdir(filepath):
#判断文件是否是txt文件
if os.path.isfile(filepath+x) and os.path.splitext(x)[1]=='.txt':
a=wordcount(filepath+x)
print('%s中的数据为: '%x,a)
wordsdict=dict(Counter(wordsdict)+Counter(a))
print('最终的结果为: ',wordsdict)
——————————————————————————————
实在比较low。学习,学习