python开发_counter()

转载自:http://www.cnblogs.com/hongten/p/hongten_python_counter.html

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

下面是我做的demo:

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

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

运行效果:

测试的文件:

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

代码部分:

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

#python counter object

from collections import *
import os

def get_counter():
    '''get the Counter object'''
    return Counter()

def str_to_list(s):
    '''
    a string covert to list,
    return an empty list if the string equal None
    '''
    if s != None:
        return [x for x in s]
    else:
        return []

def counter(c, l):
    '''统计列表l中每个单词的出现次数,最后返回一个Counter对象'''
    for word in l:
        c[word] += 1
    return c

def get_file_str(path):
    '''打开指定的文件,并且把文件中的内容以字符串的形式返回'''
    if os.path.exists(path):
        temp_str = ''
        with open(path, 'r') as pf:
            for line in pf:
                temp_str += line
            return temp_str
    else:
        print('the file [{}] is not exist!'.format(path))

def test_str():
    #使用自定义字符串测试
    #统计自定义字符串中每个字符出现的次数
    cnt = get_counter()
    temp_str = 'hello,i\'m Hongten,welcome to my space!'
    temp_list = str_to_list(temp_str)
    cnt = counter(cnt, temp_list)
    print(cnt)

def test_file():
    '''
    读取一个文件,把文件中的内容转化为字符串
    统计该字符串中每个字符串出现的次数
    '''
    cnt = get_counter()
    temp_path = 'c:\\temp.txt'
    temp_str = get_file_str(temp_path)
    temp_list = str_to_list(temp_str)
    cnt = counter(cnt, temp_list)
    print(cnt)
    
def main():
    test_str()
    print('#' * 50)
    test_file()

if __name__ == '__main__':
    main()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值