#第 0006 题: 你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。
import re,os
re_word=re.compile(r'[a-z]+')
#获得当前目录下文件后缀为txt的文档,并返回其名称
def get_files():
cwd=os.getcwd()
txt_name=[]
dirlist=list(os.listdir(cwd))
for dir in dirlist:
if dir.split('.')[-1]=='txt':
txt_name.append(dir)
print(txt_name)
return txt_name
#对每个文档得到其中的单词
def get_words(object):
txt_path = object
with open(txt_path,"r") as txt:
txt_r=txt.read()
txt=txt_r.lower()
word_list=re_word.findall(txt)
print("%s's word:%s"%(object,word_list))
return word_list
#计算每个文档的词频
def count_words(object):
counts={}
for word in object:
if word in counts:
counts[word]=counts[word]+1
else:
counts[word]=1
# 也可以写成counts[word]=counts.get(word,0)+1
thewords=['the', 'a', 'to', 'of', 'a', 'i', 'in', 'and', 'you', 'your','it','that','is']
keys=list(counts.keys())
for key in keys:
if key in thewords:
counts.pop(key)
# [counts.pop(key) for key in keys if key in thewords]
items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
print(items)
for i in range(10):
word,count=items[i]
print("{0:<10}{1:>5}".format(word,count))
if __name__ == '__main__':
filenames=get_files()
for filename in filenames:
words=get_words(filename)
count_words(words)
每天一python 题 0006
最新推荐文章于 2022-07-04 10:09:44 发布