Most occurrences of a word in a file

common world in a file

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: ")
try:
    fh = open(fname)
except:
    print("File {} cannot be opened".format(fname))
    quit()

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

One comment

  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 Reply

Your email address will not be published. Required fields are marked *