前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python开发_counter()

python开发_counter()

作者头像
Hongten
发布2018-09-13 12:31:37
3570
发布2018-09-13 12:31:37
举报
文章被收录于专栏:HongtenHongten

python的API中,提到了Counter,它具有统计的功能

下面是我做的demo:

1.统计自定义字符串中每个字符出现的次数

2.读取一个文件,把文件中的内容转化为字符串,统计该字符串中每个字符串出现的次数

运行效果:

测试的文件:

==================================

代码部分:

==================================

代码语言:javascript
复制
 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()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2013-08-14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档