[python每日一练]--0006:单词统计

题目链接:https://github.com/Show-Me-the-Code/show-me-the-code
我的github链接:https://github.com/wjsaya/python_spider_learn/tree/master/python_daily
第 0006 题:你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。


思路:

  1. 嘛。。。先读取出所有的词;
    2.利用提取出来的词做一个字典,内容为“单词:出现次数”;
  2. 一个循环,读出字典内的最大值并提取相应的单词。

代码:

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
#coding: utf-8
#Auther: wjsaya
#**第 0006 题:**你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。
import os
import re
def dir():
#检测日志目录是否存在,不存在就创建
if not os.path.exists("log"):
os.mkdir("./log")
print ("log目录不存在,已创建")
os.chdir("./log")
def dective_words():
#检测文件内的单词,并且调用word_count来统计各个单词中出现频率最高的一个
for file in os.walk("./"):
print ("当前目录为:"+os.getcwd())
for i in file[2]:
file = open(i, 'r', encoding="utf-8").read()
word_list = re.findall('([a-zA-Z0-9]+)', file)
word_dict = word_count(word_list)
max = 0
for key in word_dict.keys():
if max < int(word_dict.get(key)):
max = word_dict.get(key)
max_key = key
print ("在"+i+"中,最重要的词为:"+max_key+",共出现了"+str(max)+"次")
def word_count(word_list):
#统计单词个数
word_dict={}
frequency = 1
for single_word in word_list:
try:
number = word_dict.get(single_word)
word_dict[single_word]=number+1
except:
word_dict[single_word]=frequency
return word_dict
if __name__ == "__main__":
dir()
dective_words()

效果图:

0006


ps:因为平时上班的原因(屁,就是懒癌发作233),也是很久未更新了,作为一只python小菜鸟,个人觉得有一个这种小的练手项目还是很棒棒的,作为一只只有C语言基础(真-基础)的菜鸡,让我独立搞个练手项目出来不现实,让我去啃基础感觉又没必要,毕竟我又不是程序员(屁,就是懒得看书233),于是·我能找到的一种方式就是找小题目来给自己做,嘛,反正是让自己入门,所以如果实现思路肯定是比不过学过算法的各位大佬的啦,慢慢来吧,归根结底,不就是个玩~ᕦ༼ ✖ ਊ ✖ ༽ᕤ

0%