Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 检查文件中是否存在输入_Python_Loops_File_If Statement_While Loop - Fatal编程技术网

Python 检查文件中是否存在输入

Python 检查文件中是否存在输入,python,loops,file,if-statement,while-loop,Python,Loops,File,If Statement,While Loop,嗨,我正在检查: 如果文件中存在用户确定的输入,如果存在,则在文件中查找该输入的行号。 如果没有,则告诉用户输入不存在。 我的while循环工作正常,如果字符串存在,它会找到它的行号。然而,if语句有逻辑错误,它总是将语句传递给else。我是python新手,如果有人能帮我,那就太好了! while循环即使在找到inputWord后仍继续运行,覆盖了当前值。如果在while循环之后打印InputWord,它将始终是文本文档的最后一行 添加break语句将在找到单词后立即退出循环 while(l)

嗨,我正在检查:

如果文件中存在用户确定的输入,如果存在,则在文件中查找该输入的行号。 如果没有,则告诉用户输入不存在。 我的while循环工作正常,如果字符串存在,它会找到它的行号。然而,if语句有逻辑错误,它总是将语句传递给else。我是python新手,如果有人能帮我,那就太好了!
while循环即使在找到inputWord后仍继续运行,覆盖了当前值。如果在while循环之后打印InputWord,它将始终是文本文档的最后一行

添加break语句将在找到单词后立即退出循环

while(l)!="":
    l=f.readline()
    Line=l.split()
    if inputWord in Line:
        print("Line number",count,":",l)
        break

    count+=1
    
if inputWord in Line:
    print(inputWord,"is the",count, "most common word.")
    
else:
    print("Sorry,",inputWord,"is not one of the 4000 most common words.")

如果不确切知道文件中包含的内容,就很难确切说出您需要什么。文件是否每行只有一个单词,并且所有行都是唯一的

不管怎么说,问题似乎是,一旦您进入if inputWord in行:printLine number,count,:,l,您实际上并没有跳出循环,因此您应该在print语句的正下方添加一个break语句。换句话说,您可以正确地定位该行,但随后会继续循环并更新该行,因此当您到达最终检查时,inputWord不再在该行中,除非它恰好位于文件的最后一行(如果有意义的话)。也不清楚你为什么要把if语句放在那里。看看这是不是你想做的

import sys
f=open("/Users/emirmac/Desktop/file.txt","r")
count=1
l=0
inputWord=input("Enter a word: ")
while(l)!="":
    l=f.readline()
    Line=l.split()
    if inputWord in Line:
        print(inputWord,"is the",count, "most common word.")
        break
    count+=1
else:
    print("Sorry,",inputWord,"is not one of the 4000 most common words.")

f.close()
import sys
f=open("/Users/emirmac/Desktop/file.txt","r")
count=1
l=0
inputWord=input("Enter a word: ")
while(l)!="":
    l=f.readline()
    Line=l.split()
    if inputWord in Line:
        print(inputWord,"is the",count, "most common word.")
        break
    count+=1
else:
    print("Sorry,",inputWord,"is not one of the 4000 most common words.")

f.close()