import networkx as nx #@UnresolvedImport
from networkx.algorithms import bipartite #@UnresolvedImport
from operator import itemgetter
from random import choice
corpus = open('/home/abehl/Desktop/Corpus/songs.wx', 'r')
ALPHA = 1.5
EPSILON = 0.5
song_nodes = []
word_nodes = []
edges = zip(song_nodes, word_nodes)
B = nx.Graph(edges)
degX,degY = bipartite.degrees(B, word_nodes)
sortedSongNodesByDegree = sorted(degX.iteritems(), key=itemgetter(1))
print sortedSongNodesByDegree
song_nodes2 = []
word_nodes2 = []
Vc = list(set(word_nodes))
edges2 = zip(song_nodes2, word_nodes2)
C= nx.Graph(edges2)
for songDegreeTuple in sortedSongNodesByDegree:
for i in range(songDegreeTuple[1]):
connectedNodes = C.neighbors(songDegreeTuple[0])
VcDash = [element for element in Vc if element not in connectedNodes]
calculateBestNode(VcDash)
def calculateBestNode(VcDashsR):
nodeToProbailityDict = {}
for node in VcDashsR:
degreeOfNode = bipartite(C, [node])[1][node]
probabiltyForNode = (degreeOfNode ** ALPHA) + EPSILON
nodeToProbailityDict[node] = probabiltyForNode
在上面的python程序中,即使在程序中定义了函数'calculateBestNode',python解释器也会抛出以下错误。我在这里错过了一些东西。
NameError:name 'calculateBestNode'未定义
请原谅我在这里发布大型节目。
答案 0 :(得分:9)
Python程序从上到下执行,因此您需要在使用它之前定义该函数。一个常见的替代方法是将所有自动执行的代码放在main
函数中,并添加到文件的底部:
if __name__ == '__main__':
main()
这还有一个额外的好处,就是你现在已经编写了一个可以被其他人导入的模块。
答案 1 :(得分:3)
在程序中定义函数之前,尝试使用函数calculateBestNode()
。所以翻译不知道它存在。