【问题标题】:How to efficiently count bigrams over multiple documents in python如何在python中有效地计算多个文档的二元组
【发布时间】:2018-06-02 08:59:31
【问题描述】:

我有一组文本文档,想计算所有文本文档的二元组数。

首先,我创建一个列表,其中每个元素又是一个列表,表示一个特定文档中的单词:

print(doc_clean)
# [['This', 'is', 'the', 'first', 'doc'], ['And', 'this', 'is', 'the', 'second'], ..]

然后,我从文档中提取二元组并将它们存储在一个列表中:

bigrams = []
for doc in doc_clean:
    bigrams.extend([(doc[i-1], doc[i]) 
                   for i in range(1, len(doc))])
print(bigrams)
# [('This', 'is'), ('is', 'the'), ..]

现在,我想计算每个唯一二元组的频率:

bigrams_freq = [(b, bigrams.count(b)) 
                for b in set(bigrams)]

一般来说,这种方法是有效的,但它太慢了。 bigrams 列表非常大,总共约 5mio 条目和约 300k 独特的 bigrams。在我的笔记本电脑上,当前的方法花费了太多时间进行分析。

谢谢你帮助我!

【问题讨论】:

    标签: python nlp nltk


    【解决方案1】:

    您可以尝试以下方法:

    from collections import Counter
    from nltk import word_tokenize 
    from nltk.util import ngrams
    from nltk.stem import WordNetLemmatizer
    from nltk.corpus import stopwords
    
    stop_words = set(stopwords.words('english'))
    
    doc_1 = 'Convolutional Neural Networks are very similar to ordinary Neural Networks from the previous chapter'
    doc_2 = 'Convolutional Neural Networks take advantage of the fact that the input consists of images and they constrain the architecture in a more sensible way.'
    doc_3 = 'In particular, unlike a regular Neural Network, the layers of a ConvNet have neurons arranged in 3 dimensions: width, height, depth.'
    docs = [doc_1, doc_2, doc_3]
    docs = (' '.join(filter(None, docs))).lower()
    
    tokens = word_tokenize(docs)
    tokens = [t for t in tokens if t not in stop_words]
    word_l = WordNetLemmatizer()
    tokens = [word_l.lemmatize(t) for t in tokens if t.isalpha()]
    
    bi_grams = list(ngrams(tokens, 2)) 
    counter = Counter(bi_grams)
    counter.most_common(5)
    
    Out[82]: 
    [(('neural', 'network'), 4),
     (('convolutional', 'neural'), 2),
     (('network', 'similar'), 1),
     (('similar', 'ordinary'), 1),
     (('ordinary', 'neural'), 1)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 2017-03-15
      • 2021-08-01
      相关资源
      最近更新 更多