Python每日一题 007

时间:2023-03-09 15:27:12
Python每日一题 007

题目

你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。


很难客观的说每篇日记中最重要的词是什么,所以在这里就仅仅是将每篇日记中出现频数最高的词作为最重要的词。同时过滤掉一些词诸如【I,is,are,has,and,or】等等

代码

# -*- coding: utf-8 -*-
from collections import Counter
import re
import string
import os def get_word(filepath):
#过滤词汇
filter_word=['she','i','the','is','are','you','we','and','to','or','that','what','has',
'have','been','do','did','a','an',"'",'he','of','was','had','they','his','in','on',
'She','were','it','Mrs','The'] fp=open(filepath,'r')
content=fp.read() rule='[a-zA-Z0-9\']+'
words=re.findall(rule,content)
wordlist = Counter(words)
for i in filter_word:
wordlist[i]=0
fp.close() # most_common 按出现数次从高到底排序
return wordlist.most_common()[0] def get_file(path):
for textname in os.listdir(path):
textfile=os.path.join(path,textname)
most_important=get_word(textfile)
print("文章 ---{} ----统计".format(textname))
print("最重要的词为:{}".format(most_important[0]))
print("出现次数为:{}\n".format(repr(most_important[1]))) if __name__ == '__main__':
get_file('Text')

PS:代码很多场景无法适应,比如出现中文字符,可以更好的完善做一个格式化的字数统计工具