を構築するためのファイル.txtは読む:私が含まれているファイル名.txtを持っている辞書
交流
BCを
CD
CE
ことch
FG
FH
GH Iをしたい
デフload_graphような二つのパラメータ(グラフ、ファイル名) 辞書命名グラフとして表現し、次にキーが表す頂点を持つ関数定義値は隣接する頂点のリストです
を構築するためのファイル.txtは読む:私が含まれているファイル名.txtを持っている辞書
交流
BCを
CD
CE
ことch
FG
FH
GH Iをしたい
デフload_graphような二つのパラメータ(グラフ、ファイル名) 辞書命名グラフとして表現し、次にキーが表す頂点を持つ関数定義値は隣接する頂点のリストです
強く自己が最初とポストあなたがしようとしたとして良い習慣に問題に直面していることをスニペットのものを試してみることをお勧め/お勧めします。
1つのエッジ情報を持つファイル内の各行を考慮すると、あなたはこのような何かを行うことができます。
file_data = open("filename.txt")
graph = {}
for line in file_data:
print line
fields = line.strip("\n").split(" ")
key = fields[0]
value = fields[1]
if key not in graph:
graph[key] = [value]
else:
graph[key].append(value)
if value not in graph:
graph[value] = [key]
else:
graph[value].append(key)
希望を、これはあなたが探しているものです!
おそらく、あなたはグラフで何かしたいと思いますおそらくnetworkxやigraphのようなものを使って、エッジリストを読み込んでグラフを作成します。これらのパッケージが利用できない場合は、次のようにトリックを行う必要があります。
#!/usr/bin/env python
def edge_list_to_neighbours(edge_list, directed=False):
neighbours = dict()
for source, target in edge_list:
if not source in neighbours:
neighbours[source] = [target]
else:
neighbours[source] += [target]
if not directed: # add reverse edge
for source, target in edge_list:
if not target in neighbours:
neighbours[target] = [source]
else:
neighbours[target] += [source]
return neighbours
def read_edge_list(file_path):
with open(file_path, 'r') as f:
lines = f.readlines()
return [line.strip().split() for line in lines]
if __name__ == '__main__':
edges = read_edge_list('filename.txt')
neighbours = edge_list_to_neighbours(edges)
print neighbours