(frequency.py) Write a program that reads in the contents of a text file and dis
ID: 3710441 • Letter: #
Question
(frequency.py) Write a program that reads in the contents of a text file and displays a histogram of the frequency that words appear in the text. Requirements: - Prompt the user to enter the filename of a text file - Read the contents of that text file and count the number of times each word appears in the file - Store the words and associated counts in a dictionary as key-value pairs - Display a histogram using asterisks (recall Assignment #7) representing the frequency that the words in the file appear Notes: Make the program case-insensitive (so ‘The’ is considered the same word as ‘the’), and punctuation marks should be replaced with spaces prior to counting the words. See example below, which can be incorporated into your program: s = "Python is great. Python is useful. Python is fun. Really fun!" punctuation = [',',';','.',':','!',"'","""] for ch in punctuation: s = s.replace(ch,' ') s = s.split())
Explanation / Answer
with open(r'test_words.txt') as f:
words = [word for line in f for word in line.split()]
punctuation = [',',';','.',':','!',"'","""]
count = 0
count2 = 0
for item in words:
for item2 in item:
if item2 in punctuation:
item = item.replace(item2,'')
words[count] = item
item = item.lower()
#item = item.split()
words[count2] = item
count+=1
count2+=1
dict2 = {}
for word in words:
if word in dict2:
dict2[word]+=1
else:
dict2[word] = 1?
#example text file
#Ball cat ball cat piano cat piano cat, hello. world, cat;; piano world hello
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.