如果集合大小增加,则将该词作为键添加到字典中,值为集合的新长度
如果这个集合的大小增加了(说明这个词之前没有被处理过),那么就把这个词作为键添加到字典里,值就是集合的新大小。接着用另一个循环,显示字典里的词和它们的值,这个值代表了程序发现这些词的顺序。
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
1 个回答
0
根据你的评论,我来回答一下...
你应该用的不是这个:
for word in text.lower().split():#split text into words
[...]
print (freq)
而是这个:
for word in text.lower().split():#split text into words
[...]
print (freq)
这样的话,你就能在遇到所有单词后再打印一次。
每当你遇到类似的问题时,确保你的 print
语句放在正确的位置总是很重要的。