python - 优化给定字符串中单词列表的出现次数(Python)
问题描述
我正在创建一个计算searched_words
传递字符串中出现的函数。结果是一个字典,其中匹配的单词作为键,它们的出现作为值。
我已经创建了一个函数来完成这个,但它的优化很差。
def get_words(string, searched_words):
words = string.split()
# O(nm) where n is length of words and m is length of searched_words
found_words = [x for x in words if x in searched_words]
# O(n^2) where n is length of found_words
words_dict = {}
for word in found_words:
words_dict[word] = found_words.count(word)
return words_dict
print(get_words('pizza pizza is very cool cool cool', ['cool', 'pizza']))
# Results in {'pizza': 2, 'cool': 3}
我试图使用Counter
Pythoncollections
模型中的功能,但似乎无法重现所需的输出。似乎使用set
数据类型也可以解决我的优化问题,但我不确定如何在使用集合时计算单词出现次数。
解决方案
您认为使用以下方法有一个很好的解决方案是正确的Counter
:
from collections import Counter
string = 'pizza pizza is very cool cool cool'
search_words = ['cool', 'pizza']
word_counts = Counter(string.split())
# If you want to get a dict only containing the counts of words in search_words:
search_word_counts = {wrd: word_counts[wrd] for wrd in search_words}
推荐阅读
- dart - 用颤振绘制虚线弧
- swift - 我有一个“UIImage”,我想将其转换为 NSData 以上传到 firebase 存储
- amazon-web-services - AWS Cloudfront CacheBehavior 的 PathPattern 中可接受的通配符
- c - 在从标准输入读取的while循环中捕获EOF字符
- python-3.x - 有没有办法让 Splash 等到站点上的所有 java 脚本加载?
- c++ - 修改内存区域 - 返回 0xCC VC++
- c - 执行 make 时出错:mingw32-make: *** No rule to make target
- java - “请求的资源不支持 http 方法 'GET'” - 但我没有使用 C# 或 asp.net,我是发出请求的人
- r - 编写循环以一次在多个列表上执行
- reactjs - React 应用程序未登录到控制台或终端窗口