每天一python 题 0006

#第 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)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值