in python file: https://www.dropbox.com/s/0ftwpjgg8uwzpyr/HarryPotterAndTheSorce
ID: 3717618 • Letter: I
Question
in python
file: https://www.dropbox.com/s/0ftwpjgg8uwzpyr/HarryPotterAndTheSorcerersStone.txt?dl=0
Write a program that reads the contents of the text file called
HarryPotterAndTheSorcerersStone.txt. The program should create a dictionary in which the keys are the individual words found in the file and the values are the number of times each word appears. For example, if the word “the” appears 128 times, the dictionary would contain anelement with ‘the’ as the key and 128 as the value. The program should either display the frequency of each word or create a second file containing a list of each word and its frequency
Explanation / Answer
def main(): d = {} with open('HarryPotterAndTheSorcerersStone.txt', 'r') as f: for line in f: words = line.strip().split() for word in words: if word not in d: d[word] = 0 d[word] += 1 for word, count in d.items(): print(word + ' ' + str(count)) main()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.