使一個2D 20×20陣列,循環通過每個輸入字符串,以及使用該字符串更新矩陣:
adjacency_matrix = [[0 for _ in range(20)] for _ in range(20)]
def get_lines(filename):
"""Returns the lines in the file"""
with open(filename, 'r') as fp:
return fp.readlines()
def update_matrix(matrix, mapping, string):
"""Update the given adjacency matrix using the given string."""
words = [_ for _ in re.split("\s+", string) if _ in mapping.keys()]
for word_1 in words:
for word_2 in words:
matrix[mapping[word_1]][mapping[word_2]] += 1
if __name__ == "__main__":
words_in_matrix = ["X-men", "awesome", "good", "bad", ... 16 more ...]
mapping = {word: index for index, word in enumerate(words_in_matrix)}
for line in get_lines("ibdb.txt"):
update_matrix(adjacency_matrix, mapping, line)
print(adjacency_matrix)
類似於update_matrix
一個函數可能是有用的,以matrix
作爲鄰接矩陣,mapping
一個將詞語映射到鄰接矩陣中的索引,以及string
您的示例評論。
您需要根據需要進行修改。輸入可能有周期或其他噪聲字符,這些字符需要被去除。
你在這種情況下定義爲「鄰接」是什麼?你的問題不清楚。 – JDong
@JDong我很抱歉我英語能力差。審稿人寫這句話。 「X戰警非常棒」。有20x20矩陣。第二排是「X戰警」,第四欄是「超棒」。如果數據中有「X-Men is awsome」,則矩陣中的(2,4)將加1個頻率。 – Rejeena
只是爲了確認,你的鄰接矩陣是對稱的,因爲你有一個無向圖,對嗎? – JDong