mardi 17 novembre 2020

Check if the input exists in a file

Hi I am trying to check:

  • If the user determined input exists in the file and if it does then find the line number of that input in the file.
  • If it doesn't then tell the user that the input doesn't exist.
    My while loop works fine, and it finds the line number of the string if it exists. However my if statement has a logic error, it always passes the statement to else. I am new to python, if someone can help that would be great!
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.")

Aucun commentaire:

Enregistrer un commentaire