我正在尝试从文本文档创建对称字矩阵。

例如:
text =“芭芭拉是好人。芭芭拉是本尼的 friend 。本尼是坏人。”

我已经使用nltk标记了文本文档。现在,我想计算一下其他单词在同一句子中出现了多少次。从上面的文本中,我想创建下面的矩阵:

        Barbara good    friends Benny   bad
Barbara 2   1   1   1   0
good    1   1   0   0   0
friends 1   0   1   1   0
Benny   1   0   1   2   1
bad     0   0   1   1   1

请注意,对角线是单词的频率。由于芭芭拉与芭芭拉一起出现在句子中的次数与芭芭拉一样多。我希望不要过多计算,但是如果代码变得太复杂,这并不是一个大问题。

最佳答案

首先,我们对文本进行标记化,遍历每个句子,遍历每个句子中单词的所有成对组合,然后将计数存储在嵌套的dict中:

from nltk.tokenize import word_tokenize, sent_tokenize
from collections import defaultdict
import numpy as np
text = "Barbara is good. Barbara is friends with Benny. Benny is bad."

sparse_matrix = defaultdict(lambda: defaultdict(lambda: 0))

for sent in sent_tokenize(text):
    words = word_tokenize(sent)
    for word1 in words:
        for word2 in words:
            sparse_matrix[word1][word2]+=1

print sparse_matrix
>> defaultdict(<function <lambda> at 0x7f46bc3587d0>, {
'good': defaultdict(<function <lambda> at 0x3504320>,
    {'is': 1, 'good': 1, 'Barbara': 1, '.': 1}),
'friends': defaultdict(<function <lambda> at 0x3504410>,
    {'friends': 1, 'is': 1, 'Benny': 1, '.': 1, 'Barbara': 1, 'with': 1}), etc..

这本质上就像一个矩阵,因为我们可以索引sparse_matrix['good']['Barbara']并获取数字1,索引sparse_matrix['bad']['Barbara']并获取0,但实际上我们不存储从未出现过的任何单词的计数,0只是由defaultdict仅在您要求时使用。在执行此操作时,这确实可以节省大量内存。如果由于某种类型的线性代数或其他计算原因而需要密集矩阵,则可以这样获得:
lexicon_size=len(sparse_matrix)
def mod_hash(x, m):
    return hash(x) % m
dense_matrix = np.zeros((lexicon_size, lexicon_size))

for k in sparse_matrix.iterkeys():
    for k2 in sparse_matrix[k].iterkeys():
        dense_matrix[mod_hash(k, lexicon_size)][mod_hash(k2, lexicon_size)] = \
            sparse_matrix[k][k2]

print dense_matrix
>>
[[ 0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  1.  1.  1.  1.  0.  1.]
 [ 0.  0.  1.  1.  1.  0.  0.  1.]
 [ 0.  0.  1.  1.  1.  1.  0.  1.]
 [ 0.  0.  1.  0.  1.  2.  0.  2.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  1.  1.  1.  2.  0.  3.]]

我建议您查看http://docs.scipy.org/doc/scipy/reference/sparse.html以了解其他处理矩阵稀疏性的方法。

关于python - 使用nltk的python对称词矩阵,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17458751/

10-12 00:22
查看更多