Answer to Question #349709 in Python for Nana

Question #349709

Write a program that reads several lines of text from a text file named “data.txt” and prints a table indicating the number of one-

letter words, two-letter words, three-letter words, etc. appearing in the text. For example, if the text file contains Whether ‘tis nobler in the mind to suffer the output should be:

Word Length. Occurrences

1 0

2 2

3 2

4 2 (including ‘tis)

5 0

6 2

7 1


1
Expert's answer
2022-06-10T08:29:41-0400
import re

map = {}
with open('data.txt') as f:
    data = f.read()
    words = [re.sub(r"[\.,?!;]", "", str) for str in data.split()]
    for word in words:
        word_len = len(word)
        if word_len not in map:
            map[word_len] = 1
        else:
            map[word_len] += 1

    for i in range(1, max(map.keys()) + 1):
        print(i, map[i] if i in map else 0)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS