Most occurrences of a word in a file

4.5/5 - (4 votes)

Find the word with the most occurrences in a file and display the word and the number of occurrences.

get() method

Get looks up values in a dictionary, but unlike square brackets, get returns None if the key isn’t found.

Read more about Dictionaries in Python.

fname = input("Enter the file name: ")
    fh = open(fname)
    print("File {} cannot be opened".format(fname))

counts = dict()
for line in fh:
    words = line.split()
# Don't need to strip() because the split() strip for us automatically, it ignores spaces at the end  
    for word in words:
        counts[word] = counts.get(word, 0) + 1

max_count = None
cword = None
for key, value in counts.items():
    if max_count is None or value > max_count:
        cword = key
        max_count = value

print("The word {} appear {} times".format(cword, max_count))

Hello there!

I hope you find this post useful!

I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

subscribe youtube

1 thought on “Most occurrences of a word in a file”

  1. import collections
    wordstring = “””Google News is a news aggregator app developed by Google. It presents a continuous flow of articles organized from thousands of publishers and magazines. Google News is available as an app on Android, iOS, and the Web. Google released a beta version in September 2002 and the official app in January 2006.”””
    wordlist = wordstring.split()

    You can make use of counter from collections like freq=collections.Counter(wordlist)


Leave a Comment