我会首先设置类似以下内容。可能添加某种标记化;尽管对于您的示例,不需要。
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
like
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']]
。