您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python更快的字典替代?

5b51 2022/1/14 8:22:56 python 字数 3117 阅读 556 来源 www.jb51.cc/python

参见英文答案 > Is there anything faster than dict()?????????????????????????????????????3个 我正在使用Naive Bayes分类器创建一个简单的情绪挖掘系统. 为了训练我的分类器,我有一个文本文件,其中每行包含一个令牌列表(从推文生成)和相关的情绪(0表示-ve,4表示正数). 例如: 0 @ switchfoot ht

概述

为了训练我的分类器,我有一个文本文件,其中每行包含一个令牌列表(从推文生成)和相关的情绪(0表示-ve,4表示正数).

例如:

0 @ switchfoot http : //twitpic.com/2y1zl - Awww,that 's a bummer . You shoulda got David Carr of Third Day to do it . ; D
0 spring break in plain city ... it 's sNowing
0 @ alydesigns i was out most of the day so did n't get much done
0 some1 hacked my account on aim Now i have to make a new one
0 really do n't feel like getting up today ... but got to study to for tomorrows practical exam ...

现在,我正在尝试做的是每个令牌,计算它在正推文中出现的次数,以及它在负推文中出现的次数.然后,我计划使用这些计数来计算概率.我正在使用内置字典来存储这些计数.键是标记,值是大小为2的整数数组.

问题是这段代码启动速度非常快,但速度越来越慢,当它处理了大约20万条推文时,它变得非常慢 – 大约每秒推文一次.由于我的训练集有160万条推文,这太慢了.
我的代码是这样的:

def compute_counts(infile):
    f = open(infile)
    counts = {}
    i = 0
    for line in f:
        i = i + 1
        print(i)
        words = line.split(' ')
        for word in words[1:]:
            word = word.replace('\n','').replace('\r','')
            if words[0] == '0':
                if word in counts.keys():
                    counts[word][0] += 1
                else:
                    counts[word] = [1,0]
            else:
                if word in counts.keys():
                    counts[word][1] += 1
                else:
                    counts[word] = [0,1]
    return counts

我该怎么做才能让这个过程更快?更好的数据结构?

编辑:不重复,问题不是关于比一般情况下的dict更快的东西,而是在这个特定的用例中.

只要把数字放在计数中.

或者使用defaultdict.
https://docs.python.org/2/library/collections.html#collections.defaultdict

总结

以上是编程之家为你收集整理的Python更快的字典替代?全部内容,希望文章能够帮你解决Python更快的字典替代?所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶