【问题标题】:Check if the input exists in a file检查输入是否存在于文件中
【发布时间】:2020-11-18 04:41:21
【问题描述】:

您好,我正在检查:

  • 如果用户确定文件中存在输入,如果存在,则在文件中查找该输入的行号。
  • 如果不存在,则告诉用户输入不存在。
    我的 while 循环工作正常,它会找到字符串的行号(如果存在)。但是我的 if 语句有一个逻辑错误,它总是将语句传递给 else。我是 python 新手,如果有人可以提供帮助,那就太好了!
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("Line number",count,":",l)

    count+=1

f.close()

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

【问题讨论】:

    标签: python loops file if-statement while-loop


    【解决方案1】:

    while 循环在找到inputWord 后继续运行,覆盖当前值。如果您在 while 循环之后执行 print(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.")
    

    【讨论】:

      【解决方案2】:

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

      无论如何,问题似乎在于,一旦您到达if inputWord in Line: print("Line number",count,":",l),您实际上并没有跳出循环,因此您应该在您的打印语句下方添加一个break 语句。换句话说,您正确定位了该行,但随后您继续循环并且Line 得到更新,所以当您到达最终检查时,inputWord 不再在Line 中(除非它恰好在最后一行如果这有意义的话,请删除该文件。目前还不清楚您为什么要在其中放置该 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()
      

      【讨论】:

        猜你喜欢
        • 2014-12-03
        • 1970-01-01
        • 2013-09-19
        • 2013-06-04
        • 2011-05-14
        • 1970-01-01
        • 2012-11-06
        • 1970-01-01
        • 2012-03-14
        相关资源
        最近更新 更多