首页 > 解决方案 > 程序无法识别 for 循环中的条件语句

问题描述

如果在我创建的文本文件中找不到用户输入的输入,我正在尝试打印“无”。如果在文本文件中找到单词,它也应该打印。

我现在的问题是它没有同时做两个条件。如果我要删除“不在 user_pass 中的行”,它将不会打印任何内容。我只是希望用户能够知道用户输入的字符串是否可以在文件中找到,如果找不到,将打印该行或“无”。

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

我的代码如下:

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")

标签: pythonpython-3.xconditional

解决方案


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

@编辑

这是我解决问题的方法:

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()......你永远不会知道!!)如果如果您单击该绿色复选标记,我将不胜感激:)

推荐阅读