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
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)
Comments
Leave a comment