在python的API中,提到了Counter,它具有统计的功能
下面是我做的demo:
1.统计自定义字符串中每个字符出现的次数
2.读取一个文件,把文件中的内容转化为字符串,统计该字符串中每个字符串出现的次数
运行效果:
测试的文件:
==================================
代码部分:
==================================
1 #python counter object
2
3 from collections import *
4 import os
5
6 def get_counter():
7 '''get the Counter object'''
8 return Counter()
9
10 def str_to_list(s):
11 '''
12 a string covert to list,
13 return an empty list if the string equal None
14 '''
15 if s != None:
16 return [x for x in s]
17 else:
18 return []
19
20 def counter(c, l):
21 '''统计列表l中每个单词的出现次数,最后返回一个Counter对象'''
22 for word in l:
23 c[word] += 1
24 return c
25
26 def get_file_str(path):
27 '''打开指定的文件,并且把文件中的内容以字符串的形式返回'''
28 if os.path.exists(path):
29 temp_str = ''
30 with open(path, 'r') as pf:
31 for line in pf:
32 temp_str += line
33 return temp_str
34 else:
35 print('the file [{}] is not exist!'.format(path))
36
37 def test_str():
38 #使用自定义字符串测试
39 #统计自定义字符串中每个字符出现的次数
40 cnt = get_counter()
41 temp_str = 'hello,i\'m Hongten,welcome to my space!'
42 temp_list = str_to_list(temp_str)
43 cnt = counter(cnt, temp_list)
44 print(cnt)
45
46 def test_file():
47 '''
48 读取一个文件,把文件中的内容转化为字符串
49 统计该字符串中每个字符串出现的次数
50 '''
51 cnt = get_counter()
52 temp_path = 'c:\\temp.txt'
53 temp_str = get_file_str(temp_path)
54 temp_list = str_to_list(temp_str)
55 cnt = counter(cnt, temp_list)
56 print(cnt)
57
58 def main():
59 test_str()
60 print('#' * 50)
61 test_file()
62
63 if __name__ == '__main__':
64 main()