6

我正在尝试从文本文档创建一个对称的单词矩阵。

例如: text = "Barbara 很好。Barbara 和 Benny 是朋友。Benny 很坏。"

我已经使用 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

注意对角线是单词的频率。因为芭芭拉和芭芭拉一起出现在一个句子中的频率和芭芭拉一起出现的频率一样高。我希望不要多计,但如果代码变得太复杂,这不是一个大问题。

4

2 回答 2

7

首先,我们对文本进行标记,遍历每个句子,并遍历每个句子中单词的所有成对组合,并将计数存储在嵌套中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以了解其他处理矩阵稀疏性的方法。

于 2013-07-03T23:21:06.773 回答
3

我会首先设置类似以下内容。可能添加某种标记化;尽管对于您的示例,不需要。

text = """Barbara is good. Barbara is friends with Benny. Benny is bad."""
allwords = text.replace('.','').split(' ')
word_to_index = {}
index_to_word = {}
index = 0
for word in allwords:
    if word not in word_to_index:
         word_to_index[word] = index
         index_to_word[index] = word
         index += 1
word_count = index

>>> index_to_word
{0: 'Barbara',
 1: 'is',
 2: 'good',
 3: 'friends',
 4: 'with',
 5: 'Benny',
 6: 'bad'}

>>> word_to_index
{'Barbara': 0,
 'Benny': 5,
 'bad': 6,
 'friends': 3,
 'good': 2,
 'is': 1,
 'with': 4}

然后声明一个适当大小的矩阵(word_count x word_count);可能使用numpylike

import numpy
matrix = numpy.zeros((word_count, word_count))

或者只是一个嵌套列表:

matrix = [None,]*word_count
for i in range(word_count):
    matrix[i] = [0,]*word_count

请注意,这很棘手,并且类似的东西matrix = [[0]*word_count]*word_count不起作用,因为它会创建一个包含 7 个对同一内部数组的引用的列表(例如,如果您尝试该代码然后执行matrix[0][1] = 1,您会发现matrix[1][1],matrix[2][1]等也将更改为 1 )。

然后你只需要遍历你的句子。

sentences = text.split('.')
for sent in sentences:
   for word1 in sent.split(' '):
       if word1 not in word_to_index:
           continue
       for word2 in sent.split(' '):
           if word2 not in word_to_index:
               continue
           matrix[word_to_index[word1]][word_to_index[word2]] += 1

然后你得到:

>>> matrix

[[2, 2, 1, 1, 1, 1, 0],
 [2, 3, 1, 1, 1, 2, 1],
 [1, 1, 1, 0, 0, 0, 0],
 [1, 1, 0, 1, 1, 1, 0],
 [1, 1, 0, 1, 1, 1, 0],
 [1, 2, 0, 1, 1, 2, 1],
 [0, 1, 0, 0, 0, 1, 1]]

或者如果你想知道“Benny”和“bad”的频率是什么,你可以问matrix[word_to_index['Benny']][word_to_index['bad']]

于 2013-07-03T22:56:53.967 回答