在循环运行时组合具有相同键的字典?

发布于 2025-01-11 05:57:32 字数 700 浏览 1 评论 0原文

我有一个函数可以生成句子中单词的频率。 我还有一个句子列表。

sentences = ["this word is used for testing", "code runs this word", "testing the code now"]

def findFreq():
    # create new dict
    # word freq finding code
    # print dict


for sen in sentences:
    findFreq(sen)

这给了我一个像这样的结果:

{'this': 1, 'word': 1, 'is': 1, 'used': 1, 'for': 1, 'testing': 1}
{'code': 1, 'runs': 1, 'this': 1, 'word': 1}
{'testing': 1, 'the': 1, 'code': 1, 'now': 1}

但我想要这样的结果:

{'this': 2, 'word': 2, 'is': 1, 'used': 1, 'for': 1, 'testing': 2, 'code': 2, 'runs': 1, 'the': 1, 'now': 1}

我已经看到了使用计数器和字典理解与 Set 的解决方案,但是如何在像上面给出的循环中运行时将它们组合在一起?

I have a function that generates the frequency of the words in a sentence.
I also have a list of sentences.

sentences = ["this word is used for testing", "code runs this word", "testing the code now"]

def findFreq():
    # create new dict
    # word freq finding code
    # print dict


for sen in sentences:
    findFreq(sen)

This gives me a result like:

{'this': 1, 'word': 1, 'is': 1, 'used': 1, 'for': 1, 'testing': 1}
{'code': 1, 'runs': 1, 'this': 1, 'word': 1}
{'testing': 1, 'the': 1, 'code': 1, 'now': 1}

But I want a result like this:

{'this': 2, 'word': 2, 'is': 1, 'used': 1, 'for': 1, 'testing': 2, 'code': 2, 'runs': 1, 'the': 1, 'now': 1}

I've seen solutions that use Counter and dictionary comprehension with Set, but How do I do combine them together while running in a loop like given above?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

樱娆 2025-01-18 05:57:32

如果您想保留现有代码,请让 findFreq 返回一个字典(而不是打印它)。然后在 for 循环的每次迭代中更新一个 Counter

from collections import Counter

c = Counter()
for sen in sentences:
    c.update(findFreq(sen))

print(c)

如果您想要更短的解决方案,只需使用

>>> Counter(' '.join(sentences).split())
Counter({'this': 2,
         'word': 2,
         'is': 1,
         'used': 1,
         'for': 1,
         'testing': 2,
         'code': 2,
         'runs': 1,
         'the': 1,
         'now': 1})

If you want to keep your existing code, let findFreq return a dict (instead of printing it). Then update a Counter in each iteration of the for loop.

from collections import Counter

c = Counter()
for sen in sentences:
    c.update(findFreq(sen))

print(c)

If you want a shorter solution just use

>>> Counter(' '.join(sentences).split())
Counter({'this': 2,
         'word': 2,
         'is': 1,
         'used': 1,
         'for': 1,
         'testing': 2,
         'code': 2,
         'runs': 1,
         'the': 1,
         'now': 1})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文