Hello, I am trying to figure out the word with the greatest number of a certain text using python. I got the right word but the wrong count. Where did I go wrong?


name = input("Enter file:")
if len(name) < 1:
    name = "mbox-short.txt"
handle = open(name)
lst = list(handle)
counts = dict()
for line in lst:
    if line.startswith("From"):
        words = line.split()
        for word in words:
            counts[word] = counts.get(word, 0) + 1
        # print("counts: ", counts)
        # print (words, counts[word])
        # print (counts)
bigword = None
bigcount = None
for words,counts in counts.items():
    if bigword is None or counts > bigcount:
        bigword = word
        bigcount = counts
print (bigword, bigcount)
  1. أهلًا رهف،
    هذا الكود به حل للمشكلة، يرجى قراءة التعليقات للتوضيح:

    name = input("Enter file:")
    if len(name) < 1 : name = "mbox-short.txt"
    handle = open(name)
    #creating a dictionary to store the values of interest
    sender = {}
    #picks lines beginning with 'From:', then strips the output. Formats the output and selects the email from the line. Then adds the emails and their count to the dictionary
    for line in handle:
        if line.startswith('From: '):
            line = line.rstrip().split()
            word = line[1]
            sender[word] = sender.get(word, 0) + 1
    #Creating the variables to hold the word with the largest count
    bigword = None
    bigcount = None
    #assigns the sender.items to the items in the sender dictionary. If bigcount is None or less than the current iteration variable, the new word is stored and the count is updated in bigword and bigcount respectively. 
    for word, count in sender.items():
        if bigcount is None or count > bigcount:
            bigword = word
            bigcount = count 
    print(bigword, bigcount)


    • 1
أضف اجابة

أضف اجابة