如果集合的大小增加,则将该单词作为键添加到字典中,其值为集合的新长度

发布于 2024-11-17 04:14:44 字数 806 浏览 0 评论 0原文

如果集合的大小增加(表明该单词之前没有被处理过), 将单词作为键添加到字典中,值是集合的新长度。 使用另一个循环,显示字典中的单词列表及其值, 它代表程序发现它们的顺序。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

昇り龍 2024-11-24 04:14:44

根据您的评论我的回答...

而不是

for word in text.lower().split():#split text into words
    [...]
    print (freq)

它应该是

for word in text.lower().split():#split text into words
    [...]
print (freq)

这样,一旦遇到所有单词,您就可以打印。

每当您遇到此类问题时,最好确保您的打印位于应有的位置。

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 prints are where they should be.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文