我试图在节点之间添加边缘。
我有一个文本文件,我已将其放入列表中。 第一个列表包含:
Title , Rating
[('"$weepstake$" (1979) {(#1.2)}', '10.0'),
('"\'Til Death Do Us Part" (2006) {Pilot(#1.0)}', '3.7'),
('"\'Conversations with My Wife\'" (2010)', '4.2'),
('"\'Da Kink in My Hair" (2007)', '4.2').....much more here ]
我想创建标有所有标题的节点,当两个标题具有相同的评级时,我想在它们之间创建一个边缘,所以我 - 最后 - 在一个网络中同时获得评级为10.0的所有标题等等。
到目前为止我的代码:
import networkx as nx
import string
from sys import maxint
import csv
import pprint
import re
def printStuff(labels,dG):
for index, node in enumerate(dG.nodes()):
print '%s:%d\n' % (labels[index],dG.node[node]['count'])
str1 = titleList
#print str1
get_user_info = titleList1
dG = nx.DiGraph()
for i, word in enumerate(str1):
try:
next_word = str1[i]
if not dG.has_node(word):
dG.add_node(word)
dG.node[word]['count'] = 1
else:
dG.node[word]['count'] += 1
if not dG.has_node(next_word):
dG.add_node(next_word)
dG.node[next_word]['count'] = 0
if not dG.has_edge(word, next_word):
dG.add_edge(word, next_word, weight=0)
else:
dG.edge[word][next_word]['weight'] += 1
except IndexError:
if not dG.has_node(word):
dG.add_node(word)
dG.node[word]['count'] = 1
else:
dG.node[word]['count'] += 1
except:
raise
printStuff(titleList, dG)
输出:
10.0:1
10.0:1
3.7:1
10.0:1
3.7:1
4.2:1
10.0:1
3.7:1
4.2:1
4.2:1
对于边缘:
for edge in dG.edges():
print '%s:%d\n' % (edge,dG.edge[edge[0]][edge[1]]['weight'])
输出:
(('"\'Conversations with My Wife\'" (2010)', '4.2'), ('"\'Conversations with My Wife\'" (2010)', '4.2')):0
(('"\'Da Kink in My Hair" (2007)', '4.2'), ('"\'Da Kink in My Hair" (2007)', '4.2')):0
(('"$weepstake$" (1979) {(#1.2)}', '10.0'), ('"$weepstake$" (1979) {(#1.2)}', '10.0')):0
(('"\'Til Death Do Us Part" (2006) {Pilot (#1.0)}', '3.7'), ('"\'Til Death Do Us Part" (2006) {Pilot (#1.0)}', '3.7')):0
答案 0 :(得分:3)
这个怎么样:
data = [('"$weepstake$" (1979) {(#1.2)}', '10.0'),
('"\'Til Death Do Us Part" (2006) {Pilot(#1.0)}', '3.7'),
('"\'Conversations with My Wife\'" (2010)', '4.2'),
('"\'Da Kink in My Hair" (2007)', '4.2')]
import networkx as nx
G = nx.Graph()
G.add_edges_from(data)
nx.draw(G)
如果你想要得分的边数。
len(G.edges('4.2'))
2