0

我能否以某种方式创建一个循环,该循环遍历我拥有的一些代码,并且每次它通过循环时都会a增加,并打印出底部的行?

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'])   

更新

ha[a]in str1=h[a] 包含一堆这样的列表:

['14th_century', 'Time', 'Isaac_Newton', 'Rainbow']
['14th_century', 'Time', 'Light', 'Rainbow']
['14th_century', 'Time', 'Light', 'Color', 'Rainbow']

我在想如果我可以运行一个增加ain的循环str1 = h[a],我可以得到这个输出:

Rainbow:2

Color:1

Isaac_Newton:1

Time:3

Light:2

14th_century:3

但现在它只对我选择的那一条线重要a吗?这有道理吗?

4

1 回答 1

1
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)
于 2014-04-07T17:57:25.177 回答