如果集合的大小增加,则将该单词作为键添加到字典中,其值为集合的新长度
如果集合的大小增加(表明该单词之前没有被处理过), 将单词作为键添加到字典中,值是集合的新长度。 使用另一个循环,显示字典中的单词列表及其值, 它代表程序发现它们的顺序。
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)
结果应该是这样的:
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
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 of 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据您的评论我的回答...
而不是
它应该是
这样,一旦遇到所有单词,您就可以打印。
每当您遇到此类问题时,最好确保您的
打印
位于应有的位置。Basing my answer on your comment...
Instead of
It should be
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.