如何在Python中有效地计算多个文档中的双字母组

灰烬赏金

我有一组文本文档,并且想要计算所有文本文档中的双字母组的数量。

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

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。在我的笔记本电脑上,当前的方法花费了太多时间进行分析。

感谢您的帮助!

克尔科罗夫

您可以尝试以下方法:

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)]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在R中有效地对字符串中的字母重新排序?

如何在Python中有效地计算巨大的矩阵乘法(tfidf功能)?

如何在python中有效地根据多个条件拆分文本?

如何在python中有效地将字典中的值分组

如何在Cloud Firestore中有效地获取不同集合中具有特定ID的文档?

如何在 Python 中有效地将 2 元组的所有串联计算成更长的链

如何在 Matlab 中有效地计算单个有限差分?

如何在R中有效地联接具有多个主键的表?

如何在numpy中有效地计算高斯核矩阵?

如何在SQL中有效地计算列值的出现?

如何在Pytorch中有效地计算张量?

如何在Python中有效地在多个线程和进程之间共享数据?

如何在Python中有效地将同一操作应用于多个变量?

有效地屏蔽和计算`xr.Dataset` xarray 中多个组的均值

如何在Ruby中有效地连接多个阵列?

如何在JavaScript中有效地组合多个Maybe monad?

如何在Rails中有效地更新多个实例

如何在C#中有效地并行执行多个异步调用?

如何在Dask中有效地从DataFrame转到多个Series?

如何在python 3中有效地将原始字节写入numpy数组数据

如何在 Python 中有效地搜索和访问数据帧中的某些单元格?

如何在 python 中有效地重复矩阵中的二进制模式和比率?

如何在python中有效地搜索列表

如何在python中有效地搜索列表?

如何在python中有效地对列表进行分类

如何在Python中有效地将参数解译到数据库

如何在python类列表中有效地创建编号列表

如何在Python中有效地匹配两个数组值?

如何在 Python 中有效地按段聚合