140,643 views
41 votes
41 votes
Write a function wordcount() that takes the name of a text file as input and prints the number of occurrences of every word in the file. You function should be case-insensitive so 'Hello' and 'hello' are treated as the same word. You should ignore words of length 2 or less. The results printed will be ordered from the most frequent to the least frequent. Hint: dictionary and list. Test your implementation on file great_expectations.txt

User Scatman
by
2.1k points

1 Answer

25 votes
25 votes

Answer:

Step-by-step explanation:

The following Python program uses a combination of dictionary, list, regex, and loops to accomplish what was requested. The function takes a file name as input, reads the file, and saves the individual words in a list. Then it loops through the list, adding each word into a dictionary with the number of times it appears. If the word is already in the dictionary it adds 1 to its count value. The program was tested with a file named great_expectations.txt and the output can be seen below.

import re

def wordCount(fileName):

file = open(fileName, 'r')

wordList = file.read().lower()

wordList = re.split('\s', wordList)

wordDict = {}

for word in wordList:

if word in wordDict:

wordDict[word] = wordDict.get(word) + 1

else:

wordDict[word] = 1

print(wordDict)

wordCount('great_expectations.txt')

Write a function wordcount() that takes the name of a text file as input and prints-example-1
User Yaodav
by
3.1k points