python - 程序无法识别 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")
解决方案
我认为您需要更改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")
我喜欢这种方法,因为
- 很清楚您在哪里读取文件并将其分配给变量
- 然后打印此变量,这对于调试很有用
- 子句中的内容更少
try:
(我不想隐藏我的错误,但这并不是什么大不了的事,因为你做得很好OSError
,但是如果由于某种原因OSError
发生了怎么办line = line.rstrip()
......你永远不会知道!!)如果如果您单击该绿色复选标记,我将不胜感激:)
推荐阅读
- go - 使用 Cloud Run 进行内部 CLI 的 Google Cloud 身份验证
- keras - keras compute_output_shape 不适用于自定义层
- java - 没有静态方法“getContext()”不能从静态上下文中引用
- json - plotly.js 使用高内存
- javascript - 不支持反应分析
- python - 如何使用本地计算机中的python脚本访问远程服务器(ubuntu)中的sqlite数据库文件
- mysql - 同一表上的多个内部联接
- javascript - 如何将字符串数据以块的形式写入流,而不是块
- portable-executable - 用于获取 Windows PE/COFF 文件的 ROP 链生成的 ROP 小工具工具
- ios - 有没有办法在 Swift 中实现一致性后自动调用协议方法?