我正在创建一个函数来计算每个单词在长文本中出现的次数。当我使用下面的函数作为一个简短的文本时,它运行良好,没有问题。然而,当用超长文本运行它时,它花费的时间太长,而且永远无法返回答案
我相信我下面的代码是无效的,并且有多余的部分,这使得加载时间太长。有没有更有效的方法
def analyse_frequency(x):
z = {y : x.count(y) for y in x}
return sorted(z.items(), key=lambda t: t[1], reverse = True)[:10]
Tags:
list.count
具有O(n)复杂性。在循环中运行O(n)操作将特别低效。它至少具有复杂性O(m*n),其中m是唯一单词的数量相反,您可以使用
collections.Counter
作为O(n)解决方案:要计算文件中单词的频率,请使用计数器:
这将提供一个字典输出,其中单词作为键,计数作为它们的值
如果您不想导入任何内容,那么我建议:
根据Nearo的建议,您可以通过以下方式避免if else:
相关问题 更多 >
编程相关推荐