Variables 如何修复UnboundLocalError:局部变量';文件行';分配前参考

Variables 如何修复UnboundLocalError:局部变量';文件行';分配前参考,variables,python-3.x,variable-assignment,local,Variables,Python 3.x,Variable Assignment,Local,这是我的函数,它的作用是从文件中读取文本行 这是从一个更大的程序中提取的,因此一些注释可能看起来不合适。无论如何,我需要在许多其他函数中使用函数text和file_行,但即使将它们声明为全局函数,我仍然会得到UnboundLocalError:在赋值错误之前引用的局部变量“file_行”,我不知道该怎么办 import sys text = [] case = '' file_lines = [] def read_file(file): # function to read a

这是我的函数,它的作用是从文件中读取文本行

这是从一个更大的程序中提取的,因此一些注释可能看起来不合适。无论如何,我需要在许多其他函数中使用函数text和file_行,但即使将它们声明为全局函数,我仍然会得到UnboundLocalError:在赋值错误之前引用的局部变量“file_行”,我不知道该怎么办

import sys
text = []
case = ''
file_lines = []
def read_file(file):        # function to read a file and split it into lines
    global text             #sets variable text as a global variable for use in multiple locations
    global case             #handles case sensitivity.
try:                    #tests the statement after colon
    open(file) 
except:
    print('oops no file found bearing that name')      
else:                  
    while file == '':   #if the file name is blank print error, this prevents program from crashing
        print ('error')
        filename = input('enter a file and its extension ie file.ext\n>>')
    with open(file) as f :      #opens filewith name 

        text = f.read() #read all lines of program text.
        print ("file successfully read")
        print('TEXT SENSITIVITY TURNED ON !!!!!!')
        text = text.split('\n')# breaks lines in file into list  instead of using ".readlines"
                               # so that the program doesn't count blank lines 
        case == True

    global file_lines
    file_lines = text
尝试使用read_lines变量的函数将是

def find_words(words):        
    line_num = 0    # to count the line number
    number_of_word = 0
    if case == False:
        words = words.lower()
        file_lines = [file_lines.lower() for file_lines in text]
    while "" in file_lines:
            file_lines.remove('')      
    for lines in file_lines:

        line_num += 1
        if words in lines:  #checks each for the words being looks for
           print(line_num,"...", text[line_num-1])
           number_of_word = 1
    if number_of_word == 0: #to check if the word is located in the file
        print('Words not found')

在函数find_words中,您忘记指定
find_line
是全局的。试一试

def find_words(words):
   global file_lines
   line_num = 0    # to count the line number

函数错误,因为
文件行
未在
查找单词
的范围内定义。

请修复缩进,否则我们将无法帮助您。按原样粘贴代码,全部选中,然后按Ctrl+K将其格式化为代码。另外,请包括确切的错误消息,包括堆栈跟踪,以便我们知道错误实际发生的位置。经过多次努力后完成一个更好的问题是如何在不需要大量全局变量的情况下编写此消息。john如果你能帮我做这件事,那将更棒,我刚开始学习python,所以现在我的目标就是让它也能正常工作。效率并不是真正的最高优先级是在一个单独的文件中定义为find_行的find_单词吗?如果是,您需要使用其他\u文件。查找\u行引用它,在导入其他\u文件后,由于未知原因,它现在可以工作。我重新开始并应用了您的修复程序。一座桥终于通过了。谢谢你是说
文件行