相关疑难解决方法(0)

Python timeit令人惊讶的结果:Counter()vs defaultdict()vs dict()

我用timeit获得了非常令人惊讶的结果,有人可以告诉我,如果我做错了吗?我使用的是Python 2.7.

这是文件speedtest_init.py的内容:

import random

to_count = [random.randint(0, 100) for r in range(60)]
Run Code Online (Sandbox Code Playgroud)

这些是speedtest.py的内容:

__author__ = 'BlueTrin'

import timeit

def test_init1():
    print(timeit.timeit('import speedtest_init'))

def test_counter1():
    s = """\
    d = defaultdict(int);
    for i in speedtest_init.to_count:
        d[i] += 1
    """
    print(timeit.timeit(s, 'from collections import defaultdict; import speedtest_init;'))

def test_counter2():
    print(timeit.timeit('d = Counter(speedtest_init.to_count);', 'from collections import Counter; import speedtest_init;'))


if __name__ == "__main__":
    test_init1()
    test_counter1()
    test_counter2()
Run Code Online (Sandbox Code Playgroud)

控制台输出是:

C:\Python27\python.exe C:/Dev/codility/chlorum2014/speedtest.py
2.71501962931
65.7090444503
91.2953839048

Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)

我认为默认情况下timeit()运行代码的1000000倍,所以我需要将时间除以1000000,但令人惊讶的是Counter慢于defaultdict().

这是预期的吗?

编辑:

使用dict也比defaultdict(int)更快: …

python counter timeit python-2.7 defaultdict

14
推荐指数
1
解决办法
5856
查看次数

在Python 3.3.2中计算短语频率

我一直在网上研究不同的来源,并尝试了各种方法,但只能找到如何计算独特单词的频率而不是唯一的短语.我到目前为止的代码如下:

import collections
import re
wanted = set(['inflation', 'gold', 'bank'])
cnt = collections.Counter()
words = re.findall('\w+', open('02.2003.BenBernanke.txt').read().lower())
for word in words:
    if word in wanted:
        cnt [word] += 1
print (cnt)
Run Code Online (Sandbox Code Playgroud)

如果可能的话,我还想计算本文中使用短语"中央银行"和"高通胀"的次数.我感谢您给出的任何建议或指导.

python frequency count phrase python-3.x

6
推荐指数
1
解决办法
3535
查看次数

如何获得句子文本中二元组的概率?

我有一个包含很多句子的文本。我如何使用nltk.ngrams它来处理它?

这是我的代码:

   sequence = nltk.tokenize.word_tokenize(raw) 
   bigram = ngrams(sequence,2)
   freq_dist = nltk.FreqDist(bigram)
   prob_dist = nltk.MLEProbDist(freq_dist)
   number_of_bigrams = freq_dist.N()
Run Code Online (Sandbox Code Playgroud)

但是,上面的代码假设所有句子都是一个序列。但是,句子是分开的,我猜一个句子的最后一个词与另一个句子的起始词无关。如何bigram为这样的文本创建一个?我还需要prob_dist并且number_of_bigrams基于`freq_dist。

有类似这样的问题什么是 ngram 计数以及如何使用 nltk 实现?但它们主要是关于一个单词序列。

python nltk n-gram python-3.x

6
推荐指数
1
解决办法
5472
查看次数