In: Computer Science
python question
<proverbs.txt>
All's well that ends well.
Bad news travels fast.
Well begun is half done.
Birds of a feather flock together.
Please write a program that reads the file you specify and calculates how many times each word stored in the file appears. However, ignore non-alphabetic words and convert uppercase letters to lowercase letters. For example, all's, Alls, alls are considered to be the same words.
What is the output of the Python program when the input file is specified as "proverbs.txt"? That is, in your answer, include the source codes of your word counter program and its output.
Please refer to this
ex)
fname = input("file name: ")
file = open(fname, "r")
table =dict()
for line in file :
words = line. split()
for word= line. split()
if word not in table :
table[word]= 1
else:
table[word] +=1
print(table)
Code:
#Returns False if word does not contain a digit
def anydigit(word):
return any(symbol.isdigit() for symbol in word)
import string
diction = dict()
#Path of proverbs.txt in your machine. Change it
according to your location
with open('C:/Users/Pavan Kumar/Desktop/proverbs.txt', 'r') as
reader:
for line in reader.readlines():
line = line.strip()
words = line.split(" ")
for each in words:
#If each does not contain a digit process it;Otherwise go to next
word
if (anydigit(each)) == False:
# remove punctuation symbols
tab = str.maketrans(dict.fromkeys(string.punctuation))
new_word = each.translate(tab)
#convert it to lower case
new_word = new_word.lower()
#new_word in dictionary increment count
if new_word in diction:
diction[new_word] = diction[new_word] + 1
else:
#new_word not in dictionary initialize it to 1
diction[new_word] = 1
else:
#If each contatins a digit ignore it
continue
for word in list(diction.keys()):
print(word, ":", diction[word])
Please Rate If you like the Answer.........