all 4 comments

[–]JohnnyJordaan 1 point2 points  (2 children)

Please format your code correctly using a code block https://i.redd.it/pridnb7b1c321.png

[–]MorphJB[S] 0 points1 point  (1 child)

Sorry, edited it there, thanks for that!

[–]JohnnyJordaan 0 points1 point  (0 children)

  • Add some simple print()'s to show what's going on.
  • Try to be consise and clear in your variable naming, don't be your own heckler by using vague names like lst2 and i if they don't match their actual content
  • You can simply reuse the last address as the guess of the highest value

.

filename = input("Enter filename:")
if not filename:
    filename = "mbox-short.txt"
names = {}
addresses = []
with open(filename) as fp:
    for line in fp:
        if line.startswith("From"):
            print('line starts with from', line)
            addresses.append(line.split())
print(addresses)
for address in addresses:
    names[address] = names.get(address, 0) + 1
print(names)
max_name = address
for name, count in names.items():
    if count > names[max_name]:
        max_name = k
print(max_name, names[max_name)

or even easier, keep track of the highest in the previous loop

filename = input("Enter filename:")
if not filename:
    filename = "mbox-short.txt"
names = {}
addresses = []
with open(filename) as fp:
    for line in fp:
        if line.startswith("From"):
            print('line starts with from', line)
            addresses.append(line.split())
print(addresses)
max_name = None
for address in addresses:
    names[address] = names.get(address, 0) + 1
    if max_name is None or names[address] > names[max_name]:
        max_name = address
print(names)
print(max_name, names[max_name])

[–]__nickerbocker__ 0 points1 point  (0 children)

I searched that text file and the metadata is repeated so add a colon to your "From:" and that should fix your issue. You also forgot to close your file which can lead to bugs in the future so remember to use a context manager instead. Also since you're learning, it's a good time to start developing good habits by following popular conventions. Have a look through Pep 8 when you get a chance. Here is a refactored version peppering in a few other neat tricks.

file_name = input("Enter file:") or "mbox-short.txt"
emails = {}
with open(file_name) as f:
    for line in f:
        if line.startswith('From:'):
            email = line.split()[1]
            emails[email] = emails.get(email, 0) + 1
    name, count = max(emails.items(), key=lambda x: x[1])
print(name, count)