Python:如何加快这种耗尽方法?特里?

时间:2018-05-19 16:55:33

标签: python python-3.x methods tree trie

我的语料库中包含单词之间没有空格的句子:

thenextdayonmayanarchistsstagedarallyatchicagoshaymarketsquare
abombwasthrownbyanunknownpartyneartheconclusionoftherallykillinganofficer
intheensuingpanicpoliceopenedfireonthecrowdandeachother
sevenpoliceofficersandatleastfourworkerswerekilled

我需要在字典中将每个句子与词汇分开,例如: {'the': 1, 'next':2, 'thenext':3'...}这些数字只是频率,在这里并不重要。

输出将是分段的变体(列表),如: [[the, next, day...], [thenext, day...]...]

这是我的代码(filter_worddict是字典)

def segment(sentence):
    if sentence == '':
        yield []
    for w in filter_worddict:
        if sentence.startswith(w):
            for rest in segment(sentence[len(w):]):
                yield [w] + rest

with open('sentences.txt', 'r') as f4, open('result.txt', 'w') as f5:
    for line4 in f4:
        line4 = line4.strip()
        corpus = list(segment(line4))
        for corpusline in corpus:
            f5.write(str(corpusline) + '\n')

这段代码如何加速?我最后一次尝试使用语料库(小于30MB)时,字典为5MB,花了48h。 。 。

我环顾四周,我在Trie和Pytrie之间做出了选择,这似乎是一个很有前景的解决方案。但我不知道如何在这种情况下正确地做到这一点。提前谢谢!

0 个答案:

没有答案