第0006題:你有一個目錄,放了你一個月的日記,都是txt,為了避免分詞的問題,假設(shè)內(nèi)容都是英文,請統(tǒng)計出你認(rèn)為每篇日記最重要的詞。
解題思路:可以用剛寫的另一篇文章collections庫里面的一些方法,比如Counter()和most_common()。
代碼如下:
#! /usr/bin/env python
#coding=utf-8
import os
import re
from collections import Counter
def get_filepaths(directory):
file_paths = []
for root, directories, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
file_paths.append(filepath)
return file_paths
def counter_more_words(li):
word_dict = Counter(li)
return [i[0] for i in word_dict.most_common()[:10]]
if __name__ == '__main__':
for file in get_filepaths(r'C:\diaries'):
with open(file, 'r') as f:
word_li = re.findall("\w+", f.read())
print " ".join(counter_more_words(word_li))