gpt4 book ai didi

Python 抛出奇怪的 NameError : name is not defined

转载 作者:太空宇宙 更新时间:2023-11-04 06:57:33 25 4
gpt4 key购买 nike

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' is not defined

请原谅我在这里发布了一个大型程序。

最佳答案

一个Python程序是自上而下执行的,所以在使用之前需要先定义函数。一个常见的替代方法是将所有自动执行的代码放在 main 函数中,并在文件底部添加:

if __name__ == '__main__':
main()

这还有一个额外的好处,即您现在已经编写了一个可以被其他人导入的模块。

关于Python 抛出奇怪的 NameError : name <function_name> is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6526856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com