Coursea-py4e-ex_09_04中的代码解析-字典-dictionary

本程序通过读取文本文件,统计并找出发送邮件最多的发件人。利用Python字典记录每封邮件的发送次数,最终输出最频繁的发件人及其发送数量。
// An highlighted block
'''
9.4 Write a program to read through the mbox-short.txt and
figure out who has sent the greatest number of mail messages.
The program looks for 'From ' lines and
takes the second word of those lines as the person who sent the mail.
The program creates a Python dictionary that
maps the sender's mail address to a count of the number of times they appear in the file.
After the dictionary is produced,
the program reads through the dictionary using a maximum loop to find the most prolific committer.
'''


name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
count = dict()    #初始化一个字符串
greatkey = None   #不赋予其任何类型
greatvalues = None
#将文件按行打开,并找到其中以From开头的行,取出此行中的第二个字符串并对其进行计数操作
for line in handle:
    words = line.split()
    if len(words)<3 or words[0]!='From':    #并找到其中以From开头的行
        continue
    count[words[1]] = count.get(words[1], 0) + 1   #计数
#遍历字典中的每一个键和值,找出值最大的键值对,
for k,v in count.items():
    if greatvalues is None or v>greatvalues:   #找出值最大的键值对
        greatkey = k
        greatvalues = v
print(greatkey,greatvalues)

总结:本章主要介绍了字典的使用方法,确实是很有用的一个数据结构,用来做数据分析很有用。可以计算出现最多的字符串。

疑问:但似乎这种分割方法对中文并不适用,因为因为英文每个单词之间用空格隔开,但是中文每一个字都是独立的,那么问题来了!要如何拆解中文中的字词呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值