Reputation: 45
So I am trying to get this program to count all the words and the number of times each word is used and put it in a dictionary with a count. It seems to be counting the words correctly but I can't get it to print the correct word with the count.
import urllib.request
words_to_count={}
url='http://www.cs.uoregon.edu/Classes/15F/cis122/data/alice1.txt'
with urllib.request.urlopen(url) as webpage:
for line in webpage:
line=line.strip()
line=line.decode('utf-8')
line=line.lower()
if len(line)>0:
line_list=line.split(" ")
for word in line_list:
if word in words_to_count:
words_to_count[word
]+=1
else:
words_to_count[word]=1
for words in sorted(words_to_count):
count=words_to_count [words]
show_word=format(word,'<12s')
show_count=format( count,'6d')
print(show_word, show_count)
Upvotes: 0
Views: 118
Reputation: 2117
This is because of this line:
show_word=format(word,'<12s')
You are using word
, but you should have using words
as introduced in the for-loop.
word
is a variable from your previous for-loop.
Upvotes: 1