157k views
0 votes
5) Write a program to read text to end-of-file, and print a count of word lengths, i.e. the total number of words of length 1 which occurred, the number of length 2, and so on. Define a word to be a sequence of alphabetic characters. You should allow for word lengths up to 25 letters. A typical output should be like this: length 1 : 10 occurrences length 2 : 19 occurrences length 3 : 127 occurrences length 4 : 0 occurrences length 5 : 18 occurrences

1 Answer

4 votes

Answer:

Step-by-step explanation:

The following code is written in Python. It is a function that takes in the name of the file to be read and the size of the word. Then the function reads the file, removes whitespace and commas, splits the text into words, and scans the words for all the words that have the same length as the number passed. It counts all those words and prints out the number of occurrences of words of that length.

def countOccurrences(file_name, word_size):

f = open(file_name, 'r')

text = f.read()

text = text.replace(',', '')

split_text = text.split(' ')

occurrences = 0

for word in split_text:

if len(word) == word_size:

occurrences += 1

print("Length 1: " + str(occurrences) + " occurrences")

5) Write a program to read text to end-of-file, and print a count of word lengths-example-1
User Lisyarus
by
5.1k points