Respuesta :
Answer:
Answer:
'''
This is script makes use of dictionaries to get all the words in a file and the
number of times they occur.
'''
#section 1
import string
dic = {}
textFile=open("Text.txt","r")
# Iterate over each line in the file
for line in textFile.readlines():
tex = line
tex = tex.lower()
tex=tex.translate(str.maketrans('', '', string.punctuation))#removes every punctuation
#section 2
new = tex.split()
for word in new:
if word not in dic.keys():
dic[word] = 1
else:
dic[word] = dic[word] + 1
for word in sorted(dic):
print(word, dic[word], '\n')
textFile.close()
Explanation:
The programming language used is python.
#section 1
The string module is imported because of the string operations that need o be performed. Also, an empty list is created to hold the words and the number of times that they occur and the file is opened in the read mode, because no new content is going to be added to the file.
A FOR loop is used to iterate through every line in the file and assigns each line to a variable one at a time, and each line is converted to lowercase and punctuation is stripped off every word in each line.
This processing is needed in order for the program o accurately deliver the number of occurrences for each individual word in the text.
#section 2
Each line is converted to a list using the split function, this is done so that a FOR loop can iterate over each word. The FOR loop, iterates over each word in the list and the IF statement checks if the word is already in the dictionary, if the word id in the dictionary, it increases the number of occurrences, if it is not in the dictionary, it adds it to the dictionary and assigns the number 1 to it.
The words are then sorted just to make it look more organised and the words and the number of times that they occur is printed to the screen.