返回单词及其在字符串中出现的次数的字典

发布于 2025-01-16 14:51:22 字数 499 浏览 1 评论 0原文

我有一大堆特定关键字,我想将其计入大字符串描述中。我想返回关键字及其在所述字符串中出现次数的字典,例如:

description = "Apples and oranges are the best fruit, I'm growing some trees outside. Apples are my favorite, oranges are cool too"
keywords = ['apples', 'oranges', 'fruit', 'trees']

我想计算这些关键字在字符串中找到的次数并返回如下内容:

{'apples': 2, 'oranges' 2, 'fruit': 1, 'trees': 1}

我不完全是确定如何解决这个问题,我尝试过使用 Counter,但只能弄清楚如何计算列表中的单词数。我也可以使用 NLTK 来实现此目的吗?我正在尝试想出一个可以扩展以容纳大量列表和描述的解决方案。任何正确方向的帮助将不胜感激。

I have a large list of specific keywords I would like to count in a large string description. I would like to return a dictionary of the keywords and their number of occurrences in said string, for example:

description = "Apples and oranges are the best fruit, I'm growing some trees outside. Apples are my favorite, oranges are cool too"
keywords = ['apples', 'oranges', 'fruit', 'trees']

I'd like to count the number of times these keywords are found in the string and return something like this:

{'apples': 2, 'oranges' 2, 'fruit': 1, 'trees': 1}

I'm not exactly sure how to go about this, I've tried using Counter but was only able to figure out how to count the number of words in a list. Could I also use NLTK for this? I'm trying to think of a solution I could scale up for huge lists and descriptions. Any help in the right direction would be greatly appreciated.

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

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

发布评论

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

评论(1

栀子花开つ 2025-01-23 14:51:22

使用 str.count() 尝试这种清晰简洁的字典理解:

{word: description.lower().count(word) for word in keywords}

Try this clear and concise dictionary comprehension using str.count():

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