我会先设置类似以下的内容。可能需要添加某种令牌化;但对于您的示例,不需要。
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);可以使用numpy
来实现,例如:
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']]
查询。