So this is my first post and I have only begun using python. One of my first assignments is to design a program which will count the most used words in the given text file. In my case we are using the Declaration of Independence.
Here is what i have so far, I think everything is fine up until the end were i get confused.The Problems i seem to have is with the My dictionary statements at the bottom. Any way to sort it out?
Once again i'm sorry if i sound terrible but I've only just started this so not everything is 100% accurate.
def word_freq(text_file):
""" prints the most commonly used words in the given text file
author
INPUT
text_file: the name of a text file to analyze
OUTPUT
printing the most frequently used words in the file
"""
f = open(text_file, 'r')
contents = f.read()
words = contents.split()
for i in range(len(words)):
words[i] = words[i].lower()
words[i] = words[i].strip(',:.;')
counter = dict()
for i in range(len(words)):
if words[i] not in counter:
counter[words[i]] = 1
else:
counter[words[i]] += 1
sorted_words = list(sorted(counter, key=counter.get, reverse=True))
for w in sorted_words[0:30]:
print('freq:',counter[w],'word',w)
my_dictionary
my_dictionary[‘the’] = 0
else:
my_dictionary[‘the’] += 1
Any helpful tips or solutions would be greatly appreciated.
Thanks a bunch.