程序无法识别 for 循环中的条件语句

Program not recognizing conditional statements in for loop

如果在我创建的文本文件中找不到用户输入的内容,我将尝试打印 "None"。如果在文本文件中找到 if word(s) are 行,它也应该打印。

我现在的问题是它没有执行两个条件。如果我要删除 "line not in user_pass" 它不会打印任何东西。我只是希望用户能够知道用户输入的字符串是否可以在文件中找到,如果找不到则打印该行或 "none" 。

我注释掉了那些我尝试修复我的代码但没有用的地方。

我的代码如下:

def text_search(text):
try:
    filename = "words.txt"
    with open(filename) as search:
        print('\nWord(s) found in file: ')
        for line in search:        
            line = line.rstrip() 
            if 4 > len(line):
                continue
            if line.lower() in text.lower():
                print("\n" + line)
            # elif line not in text: # the function above will not work if this conditional commented out
            #     print("None")
            #     break

            # if line not in text:  # None will be printed so many times and line.lower in text.lower() conditional will not work
            #   print("none")

except OSError:
    print("ERROR: Cannot open file.")

text_search("information")

我认为您需要将 for line in search: 更改为 for line in search.readlines(): 我认为您从未从文件中读取...您是否尝试过 print(line) 并确保你的程序正在阅读任何东西吗?

@EDIT

以下是我解决问题的方法:

def text_search(text):
    word_found = False
    filename = "words.txt"
    try:
        with open(filename) as file:
            file_by_line = file.readlines() # returns a list
    except OSError:
        print("ERROR: Cannot open file.")
    print(file_by_line) # lets you know you read the data correctly
    for line in file_by_line:        
        line = line.rstrip() 
        if 4 > len(line):
            continue
        if line.lower() in text.lower():
            word_found = True
            print("\n" + line)
    if word_found is False:
        print("Could not find that word in the file")

text_search("information")

我喜欢这种方法,因为

  1. 很清楚你在哪里读取文件并将其分配给一个变量
  2. 然后打印这个变量,方便调试
  3. try: 子句中的内容较少(我不想隐藏我的错误,但这并不是什么大问题,因为您在指定 OSError 方面做得很好,但是,如果 OSError 由于某种原因发生在 line = line.rstrip() 期间......你永远不会知道!!) 如果这对您有帮助,请点击那个绿色勾号,我将不胜感激:)

试试这个:-

def find_words_in_line(words,line):
    for word in words:
        if(word in line):
            return True;
    return False;

def text_search(text,case_insensitive=True):
    words = list(map(lambda x:x.strip(),text.split()));
    if(case_insensitive):
        text = text.lower();
    try:
        filename = 'words.txt'
        with open(filename) as search:
            found = False;
            for line in search:
                line = line.strip();
                if(find_words_in_line(words,line)):
                    print(line);
                    found = True;
            if(not found):
                print(None);
    except:
        print('File not found');

text_search('information');

没看懂你的代码,按你的要求自己做了一个