How to fix UnboundLocalError: local variable 'file_lines' referenced before assignment

How to fix UnboundLocalError: local variable 'file_lines' referenced before assignment

所以这是我的函数,用于从文件中读取文本行。

这是从一个更大的程序中提取的,因此一些评论可能看起来不合适。无论如何我需要在许多其他函数中使用函数 text 和 file_lines 但即使在将它们声明为全局函数之后我仍然得到 UnboundLocalError: local variable 'file_lines' referenced before assignment error 我不知道该怎么做做。

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_lines 是全局的。尝试

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

函数错误,因为 file_lines 没有在 find_words 的范围内定义,否则。