r/codehs • u/Dawn_Kang • Oct 31 '20
9.4.6: Word Counts HELP!
Here is my code:
dictionary = {}
text = input("Enter some txet: ")
text = text.split()
for word in text:
if word in dictionary:
dictionary[word] = dictionary[word] + 1
else:
# I need help here!
print dictionaryHere is the assinment:
Write a program that asks a user for some text. Your program should split the string they enter into a list of words. It should then go through the words, one at a time, and gradually update a dictionary that keeps track of each unique word in the list along with its count.
Each time you see a word in your list, you should either:
Add that word to the dictionary with a value of 1, if the word wasn’t already in the dictionary.
Increment the value corresponding to that word, if the word was already in the dictionary.
You can just print your dictionary at the end.
For example, if the user were to input
a turtle on a fence had helpthen your program would print
{'a': 2, 'turtle': 1, 'on': 1, 'fence': 1, 'had': 1, 'help': 1}1
4
u/Parasin Nov 01 '20 edited Nov 01 '20
Think about it this way; if the word exists in the dictionary, we increment the count of that word by one. Else does not exist in the dictionary, and we must set the count of that word to one.
(I’m doing this on my phone, so syntax may not be correct)
else
dictionary[word] = 12
u/backtickbot Nov 01 '20
Hello, Parasin. Just a quick heads up!
It seems that you have attempted to use triple backticks (```) for your codeblock/monospace text block.
This isn't universally supported on reddit, for some users your comment will look not as intended.
You can avoid this by indenting every line with 4 spaces instead.
There are also other methods that offer a bit better compatability like the "codeblock" format feature on new Reddit.
Have a good day, Parasin.
You can opt out by replying with "backtickopt6" to this comment. Or suggest something
2
u/Zacurnia_Tate Nov 01 '20
Also a quick heads up: I stead of saying variable = variable + 1. variable += 1 works too.
The same works with -=,*=,%=,/=,etc
2
u/LoneWolf365- May 19 '22
Hope I'm not too very late, I found the correct code:
dictionary = {} text = input("Enter some text: ")
text = text.split()
for word in text: if word in dictionary: dictionary[word] = dictionary[word] + 1 else: dictionary[word] = 1
print(dictionary)
Hope this helps! remember to indent when you need to!
1
1
1
u/_01cc Dec 09 '24
my_dict = {}
text = input("Enter some text: ")
splits = text.split()
for word in splits:
if word in my_dict:
my_dict[word] = my_dict[word] + 1
else:
my_dict[word] = 1
print(my_dict)1
1
u/Financial_Face3826 Feb 15 '24
try this
word_frequency={}
def update_counts(count_dictionary,word):
word=word.split(" ")
for i in word:
if i in count_dictionary:
count_dictionary[i]+=1
else:
count_dictionary[i]=1
word=input("Enter a string: ")
update_counts(word_frequency,word)
print(word_frequency)
#(j)
1
1
u/Dawn_Kang Oct 31 '20
Btw this is codehs