ITPub博客

首页 > 大数据 > 数据分析 > python写的简单分组统计脚本

python写的简单分组统计脚本

原创 数据分析 作者:lsq_008 时间:2016-03-23 21:37:28 0 删除 编辑
访问日志内容:
'asdfasd'|2222|'asdfasdf'|{'phone':'13511020335','name':'lsq','address':'asdfasdfasdfasf'}
'asdfasd'|2222|'asdfasdf'|{'phone':'13511020335','name':'lsq','address':'asdfasdfasdfasf'}
'asdfasd'|2222|'asdfasdf'|{'phone':'13810210010','name':'llj','address':'asdfasdfasdfasf'}
'asdfasd'|2222|'asdfasdf'|{'phone':'18900102987','name':'ljk','address':'asdfasdfasdfasf'}
'asdfasd'|2222|'asdfasdf'|{'phone':'13810210010','name':'llj','address':'asdfasdfasdfasf'}
'asdfasd'|2222|'asdfasdf'|{'phone':'13511020335','name':'lsq','address':'asdfasdfasdfasf'}
'asdfasd'|2222|'asdfasdf'|{'phone':'13511020335','name':'lsq','address':'asdfasdfasdfasf'}
'asdfasd'|2222|'asdfasdf'|{'phone':'13511020335','name':'lsq','address':'asdfasdfasdfasf'}
'asdfasd'|2222|'asdfasdf'|{'phone':'18900102987','name':'ljk','address':'asdfasdfasdfasf'}

统计需求:按电话和用户名来统计访问次数

可以用三种方法:

### 1. collections  Counter
from collections import Counter
l = []
for s in open('a.txt'):
    d = eval(s.split('|')[-1].strip())
    l.append(d['phone']+ '||' + d['name'])
    
Counter(l)

Counter({'13511020335||lsq': 5, '18900102987||ljk': 2, '13810210010||llj': 2})

### 2.list.count
l = []
for s in open('a.txt'):
    d = eval(s.split('|')[-1].strip())
    l.append(d['phone']+ '||' + d['name'])
a = {}
for i in l:
    if l.count(i)>=1:
        a[i] = l.count(i)
print a

>>> print a
{'18900102987||ljk': 2, '13810210010||llj': 2, '13511020335||lsq': 5}

### 3.dict in
dr = {}
for s in open('a.txt'):
    d = eval(s.split('|')[-1].strip())
    k_dr = d['phone']+ "||" + d['name']
    if k_dr in dr:
        dr[k_dr] = dr[k_dr] + 1
    else:
        dr[k_dr] = 1

>>> print dr
{'18900102987||ljk': 2, '13810210010||llj': 2, '13511020335||lsq': 5}

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10972173/viewspace-2062806/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
十余年大型金融及电信系统数据库管理经验,曾服务于中国建设银行、中国移动。对oracle,mysql数据库有深入了解。 擅长python开发,独立开发了开源数据库自动化监控运维平台Power Monitor。

注册时间:2008-02-29

  • 博文量
    325
  • 访问量
    1244222