我正在尝试构建一个加权无向图来表示文本文件中的单词对及其频率。单词列表是'word_list'。
# Get all bigrams from the list
bigrams=[]
for i in range(len(word_list)-1):
bigrams.append((word_list[i], word_list[i+1]))
# Counter of bigrams frequency
bigram_counts = Counter(bigrams)
# Build undirected weighted graph
G = WeightedUndirectedGraph()
for k, v in bigram_counts.items():
G.add_edge(k[0], k[1], weight=v)
我得到错误:
in add_edge self.out[start][end] = weight
KeyError: 'word1'
(word1是单词列表的第一个单词)
为了构建图表,我使用了一个自制的类 WeightedUndirectedGraph(),这里只有一个带有 add_edge 函数的摘录:
class WeightedUndirectedGraph(WeightedDiGraph):
def add_edge(self, node1: Hashable, node2: Hashable, weight: float) -> None:
super().add_edge(node1, node2, weight)
super().add_edge(node2, node1, weight)
我不太理解消息错误,我被卡住了。非常感谢任何帮助!