Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 调用嵌套函数后发生NameError_Python_List_Function_File - Fatal编程技术网

Python 调用嵌套函数后发生NameError

Python 调用嵌套函数后发生NameError,python,list,function,file,Python,List,Function,File,因此,我将一个.txt文件拆分为一个列表列表(如下所示)。但是,当我尝试运行print(splitKeyword(关键字[1][0]))尝试打印关键字列表中第二个列表/元素的第一个元素时,我得到了错误:NameError:name'keywordList'未定义。我怎样才能解决这个问题 def functionOne(textFile): textFileVar = open(textFile, 'r') def splitKeyword(argument):

因此,我将一个.txt文件拆分为一个列表列表(如下所示)。但是,当我尝试运行
print(splitKeyword(关键字[1][0]))
尝试打印关键字列表中第二个列表/元素的第一个元素时,我得到了错误:
NameError:name'keywordList'未定义
。我怎样才能解决这个问题

def functionOne(textFile):
        textFileVar = open(textFile, 'r')

    def splitKeyword(argument):
        keywordList = []
        for line in argument:
            keywordList.append(line.strip().split(','))
        return keywordList

    splitKeyword(textFileVar)
    print(keywordList[1][0])

results = functionOne("text1.txt")
print(results)
这是text1.txt/textFile/textFileVar内容

你好,世界

123456

这是打印时关键字列表的样子:

[[hello, world], [123, 456]]

您的
关键字列表是函数
splitKeyword()
的本地列表,而不是函数
functionOne()
。这就是为什么会出现NameError。

关键字列表是函数splitKeyword的局部变量,函数splitKeyword返回它,因此您可以直接使用此函数并减少代码

def functionOne(textFile):
    textFileVar = open(textFile, 'r')
    def splitKeyword(argument):
        keywordList = []
        for line in argument:
            keywordList.append(line.strip().split(','))
        return keywordList

    print(splitKeyword(textFileVar))

results = functionOne("text1.txt")
print(results)
试试这个:

def functionOne(textFile):
        textFileVar = open(textFile, 'r')

    def splitKeyword(argument):
        keywordList = []
        for line in argument:
            keywordList.append(line.strip().split(','))
        return keywordList

    output = splitKeyword(textFileVar)
    print(output[1][0])
    return output

results = functionOne("text1.txt")
print(results)

查看
splitKeyword
函数中的
returnkeywordlist
。它返回值(
关键字列表
)。但在其他作用域中,您无法访问该变量,因此需要将其存储在某个位置。

您正在从函数返回,但未捕获。因此,请尝试使用keywordList=splitKeyword(textFileVar),因为keywordList是该函数的本地函数。@CosmicCat您的函数splitKeyword()返回一些内容,所以您最好使用此返回,对吗?获取它在变量中返回的内容,然后使用此变量打印它。是否需要“返回输出”?当我删除它时,我得到了我正在寻找的控制台输出,但是“None”一词正好出现在itI下面,我想这是因为您的另一行代码。但是删除它并检查是否需要。当我保留返回输出时,我没有得到任何结果,但是当我删除它时,我没有得到任何结果,这会导致任何问题吗?这是因为
results=functionOne(“text1.txt”)
。return output将返回值,因此
结果
不会为空(None),如果删除它,则函数没有任何输出,因此结果将为空。