problem0006日记关键词
第 0006题: 你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。
- 从txt文件中读出文章内容
- 使用 re.findall() 方法进行正则表达式匹配,值得注意的是 re.findall() 方法匹配后会返回一个由文章所有词组成的列表,且重复出现的单词不会被去重
- 使用 list.Counter() 方法对列表中单词出现次数进行排序,会返回一个单词—出现次数一一键值对应的字典
- 排除一些代词、冠词的干扰,即代码中使用filter_word进行的过滤词
- 使用 Counter.most_common() 方法对字典中的词按值排降序,会返回一个由许多元组所组成的列表,按值的大小依次降序排列
demo:
#!/bin/python3
import re,os
from collections import Counter
file_path = '/home/py_learning/show-me-the-code-master/problem0006'
filter_word = ['the','in','of','to','has','that','is','are','a','with','as','an']
def getCounter(filesource):
wordC = r'''[A-Za-z]+|$\d+%?$'''
with open(filesource) as f:
result = re.findall(wordC,f.read())
return Counter(result)
def run(file_path):
os.chdir(file_path)
counter_all = Counter()
for i in os.listdir(os.getcwd()):
if os.path.splitext(i)[1] == '.txt':
counter_all += getCounter(i)
for j in filter_word :
counter_all[j]=0
print (counter_all.most_common()[0][0])
if __name__ == '__main__':
run(file_path)
参考:Python Show-Me-the-Code 第 0006 题 最重要的词
参考:Python练习册 第 0006 题:你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。