本题的链接来自https://github.com/Yixiaohan/show-me-the-code

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

解析

首先用正则表达式将文章内的字全部找出来,再去掉需要过滤的词,然后再用Counter(),将出现次数最多的英语单词挑出来。

counter(1) #表示取频率第一大的数

###

代码

#coding:utf-8
import re
from collections import Counter

other_world = {'of','i','you','it','she','he','if','then','has','is','are','a','an','the','they','we'} #过滤词汇
def get_words():
    path = 'word.txt' #文件地址
    with open(path) as f: #读文件
        content = f.read().lower() #转成小写
    words = re.findall(r'[a-zA-Z]+',content) #搜索字符
    for i in other_world: #把要过滤的词汇去掉
        if i in words:
            words.remove(i)
    c = Counter(words)
    return c.most_common(1)[0] #选取频率最高的词汇

if __name__ == '__main__':
    print(get_words())