Chapter 9 :Dictionaries (Assignment)
2016-03-13 16:07
381 查看
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()
最后结果: