用Python查找文件中出现次数最多的电子邮件的程序

问题描述 投票:0回答:2

编写一个程序来读取 mbox-short.txt 并找出谁发送了最多数量的邮件。该程序查找“发件人”行,并将这些行的第二个单词作为发送邮件的人。该程序创建一个 Python 字典,将发件人的邮件地址映射到它们在文件中出现的次数。生成字典后,程序使用最大循环读取字典,以找到最多产的提交者。

name = input("Enter file:")
if len(name) < 1:
    name = "mbox-short.txt"
handle = open(name)
for line in handle:
    bigcount=0
    bigword=None
    line=line.rstrip()
    if line.startswith('From'):
        words=list()
        words=line.split()
        word=words[1]
        count=dict()
        count[word]=count.get(word,0)+1
    for i,j in count.items():
       if j>bigcount:
            bigcount=j
            bigword=i
print(bigword,bigcount)

我得到了最多出现的单词,但没有得到它正确的对应频率。请帮助我发现这个特定代码中的错误

python list file dictionary get
2个回答
1
投票

我从来不擅长调试别人的代码,因为这是双重劳动(尝试像其他人一样思考......)所以我们不这样做,而是呈现一个简短的工作版本。 (n+年前完成的...) 希望您能够阅读和比较,然后自己找出问题所在。这也是一个很好的学习习惯。

fname = input("Enter file name")
fh = open(fname)
counts = {}
lst = []

for line in fh:
    if not line.startswith("From "):
        continue
    line = line.rstrip().split()
    emails = line[1]
    lst.append(emails)
for email in lst:
    counts[email] = counts.get(email, 0) +1
print(emails, counts[email])

0
投票

尝试更换:

if line.startswith('From'):

if line.startswith('From:'): continue

希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.