Python更快的字典替代?

hoo*_*hal 7 python performance dictionary nlp

我正在使用一个简单的情绪挖掘系统Naive Bayes classifier.

为了训练我的分类器,我有一个文本文件,其中每行包含一个令牌列表(从推文生成)和相关的情绪(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 ...
Run Code Online (Sandbox Code Playgroud)

现在,我正在尝试做的是每个令牌,计算它在正推文中出现的次数,以及它在负推文中出现的次数.然后,我计划使用这些计数来计算概率.我正在使用内置字典来存储这些计数.键是标记,值是大小为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
Run Code Online (Sandbox Code Playgroud)

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

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

khe*_*ood 12

不要使用if word in counts.keys() 如果你这样做,你最终会按顺序查看按键,这dict是应该避免的.

刚刚放if word in counts.

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