Open a file called "romeo-full.txt" and construct a dictionary.
import string
# Open a file
file_handle = open('romeo-full.txt')
# Construct an empty dictionary
counts = dict()
# Loop through the file, do some processing and add the content to the dictionary
for line in file_handle:
line = line.translate(str.maketrans('', '', string.punctuation))
line = line.lower()
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
counts
Convert the dictionary into a list of tuples.
# Construct an empty list
lst = list()
# Add elememts to the list as list of tuples using the items() function.
for key, val in list(counts.items()):
lst.append((val, key))
lst
Print out the most common words in the file.
#Sort the list in reversed order to show the most common word in the file.
lst.sort(reverse=True)
#Finally, print out the tuple to produce a list of the most common word in the file.
for key, val in lst[:10]:
print(key, val)