我会首先设置类似下面的内容。可能会添加某种类型的标记;尽管对于你的例子来说没有必要。
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]]
或者有什么说“本尼”和“坏”,你可以问matrix[word_to_index['Benny']][word_to_index['bad']]
的频率,如果你是好奇。
问题是什么? –
如何从文本创建上述矩阵? – mumpy