python第六题 统计日记中的重要关键词

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

思路: 好像上一个题,先找出一个文件目录下的所有关于‘.txt’的文件,然后一个一个的进行条件的搜索。这里又学到一个新知识点:counter()的使用
还有,stop_word就是一些没有用的词汇 检查出他们很多也没什么卵用 干脆忽略他们
代码:

import re, os
from collections import Counter

# 目标文件所在目录
FILE_PATH = 'G:\python文件\文本文件'

def getCounter(articlefilesource):
'''输入一个英文的纯文本文件,统计其中的单词出现的个数'''
pattern = r'''[A-Za-z]+|\$?\d+%?$'''
with open(articlefilesource) as f:
r = re.findall(pattern, f.read())
return Counter(r)

#过滤词
stop_word = ['the', 'in', 'of', 'and', 'to', 'has', 'that', 's', 'is', 'are', 'a', 'with', 'as', 'an']

def run(FILE_PATH):
# 切换到目标文件所在目录
os.chdir(FILE_PATH)
# 遍历该目录下的txt文件
total_counter = Counter()
for i in os.listdir(os.getcwd()):
if os.path.splitext(i)[1] == '.txt':
total_counter += getCounter(i)
# 排除stopword的影响
for i in stop_word:
total_counter[i] = 0
print (total_counter.most_common()[1:5])

if __name__ == '__main__':
run(FILE_PATH)

知识点总结:
1.re.findall(): 用来匹配的 返回一个列表 将匹配的子串作为列表的一个元素
参考:http://blog.csdn.net/huangxiongbiao/article/details/45154445
2.counter()的用法
参考:http://www.pythoner.com/205.html
顾名思义,就是统计单词出现次数 返回一个字典 键值对分别对应 单词和出现次数
其中most_common()用来返回一个列表 [(),(),()] 这种形式 用来统计单词和出现个数 可以用列表的切片法返回你想要的前n个单词
counter()里边可以装iteration中的任何一个
3.os.path.splitext() 就返回一个列表 里边是两个元素 将文件名字和扩展名分开
更多关于os.path.****的用法 参考https://www.cnblogs.com/dkblog/archive/2011/03/25/1995537.html




posted @ 2018-02-01 16:19  BUSYGIRL  阅读(285)  评论(0编辑  收藏  举报