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

Solution: Key Word in a Diary, Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Date : 2015-03-09 21:25:51
# @Author : NSSimacer
# @Version : 1.0
import os
import re
def key_words_in_diary(diary):
'''
统计日记中最重要的词(这里认为是出现次数最多的词)
'''
words = []
words_dict = {}
with open(diary, 'r') as f:
for line in f:
# 分割出日记里面的词
words.extend(re.findall(r'[a-zA-Z0-9]+', line.strip()))
for word in words:
word = word.lower() # 统一单词大小写
if word not in words_dict: # 统计单词出现次数
words_dict[word] = 1
else:
words_dict[word] += 1
return words_dict, max(zip(words_dict.values(), words_dict.keys()))[1]
if __name__ == '__main__':
base_dir = 'Diaries/'
files = os.listdir(base_dir)
for f in files:
if os.path.splitext(f)[1][1:] in ['txt']:
key_words = key_words_in_diary(base_dir + f)
print 'In diary: %s\nWords are: %s\nKey word is: %s' %\
(f, key_words[0], key_words[1])

主要目的是练习 Python 操作文件和字符串。简单起见,这里认为一篇日记中出现次数最多的词是最重要的。

题目来源:Python 练习册,每天一个小程序 THX!