def printStuff(labels,dG):
for index, node in enumerate(dG.nodes()):
print '%s:%d\n' % (labels[index],dG.node[node]['count'])
dG = nx.DiGraph()
for i, word in enumerate(str1):
try:
next_word = str1[i + 1]
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=maxint - 1)
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(h[i], dG)
increasing i in a loop in python
Вопрос
Can I somehow create a loop that runs through some code I have and for every time it runs through the loop a
increases, and print out the line in the bottom?
a=0
str1 = h[a]
dG = nx.DiGraph()
for i, word in enumerate(str1):
try:
next_word = str1[i + 1]
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=maxint - 1)
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
for node in dG.nodes():
print '%s:%d\n' % (node, dG.node[node]['count'])
update
ha[a]
in str1=h[a
] contains a bunch of list like this:
['14th_century', 'Time', 'Isaac_Newton', 'Rainbow']
['14th_century', 'Time', 'Light', 'Rainbow']
['14th_century', 'Time', 'Light', 'Color', 'Rainbow']
I was thinking if I could run a loop that increases a
in str1 = h[a]
, I could get this output:
Rainbow:2
Color:1
Isaac_Newton:1
Time:3
Light:2
14th_century:3
But right now it only counts for that one line I have chosen a
to be? Does this make any sense?
Решение
Не связан с StackOverflow