Chapter 9 :Dictionaries (Assignment)

本文介绍了一个Python脚本,该脚本可以读取指定文件中的邮件地址,并统计出现频率最高的邮件地址。

这里写图片描述

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
lst2=list()
lst=list()
handle = open(name)
for line in handle:
    line=line.rstrip()
    if not line.startswith('From '):continue
    lst=line.split()
    lst2.append(lst[1])
words=dict()
for word in lst2:
    words[word]=words.get(word,0)+1

bignum=None
bigcount=None
for num,count in words.items():
    if bigcount is None or bigcount<count:
        bigcount=count
        bignum=num

print bignum,bigcount

可以把这次的代码看成两部分组成:
part 1:

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
lst2=list()
lst=list()
handle = open(name)
for line in handle:
    line=line.rstrip()
    if not line.startswith('From '):continue
    lst=line.split()
    lst2.append(lst[1])

一开始提前邮箱地址的代码和上次的没什么区别,唯一要注意的是,上次偷懒所以每次循环都打印一次找到的邮箱地址,而没有真正意义上把所有mail存入到一个list中。 所以这次新建一个lst2,调用append()方法存入所有邮箱。

顺便提一下这里的lst[1]应该是String类型的。

part2:

words=dict()
for word in lst2:
    words[word]=words.get(word,0)+1

bignum=None
bigcount=None
for num,count in words.items():
    if bigcount is None or bigcount<count:
        bigcount=count
        bignum=num

print bignum,bigcount

这里就是在dict中去寻找value最大的item,然后将它的key和value都输出.

注意:1、Python中赋初值一般是None而不是0
2、words.items()而不是words.item()

最后结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值