If the set increases in size (indicating this word has not been processed before), add the word to the dict as a key with the value being the new length o开发者_开发知识库f the set. Using another loop, display the list of words in the dict along with their value, which represents the order in which they were discovered by the program.
freq= {} # empty dict
wordSet = set() # empty set
while True:
text=input ("Write sentence:")
if not text:
print ("Finished")
break
else:
for punc in (".,?;!"):
text = text.replace (punc, "")#replace punctuation with empty string
for word in text.lower().split():#split text into words
wordSet.add(word)#loop and add words to the set
count =len(wordSet)
freq[word] = count
print (freq)
The result should look like this:
Enter text: how now brown cow
how 1
now 2
cow 4
brown 3
Enter text: the cow jumped over the moon
brown 3
cow 4
jumped 6
over 7
moon 8
how 1
the 5
now 2
Basing my answer on your comment...
Instead of
for word in text.lower().split():#split text into words
[...]
print (freq)
It should be
for word in text.lower().split():#split text into words
[...]
print (freq)
So that you're printing once all the words have been encountered.
Whenever you have a problem like this, it's always good to make sure your print
s are where they should be.
精彩评论