Home > Enterprise >  why is my code returning 0 even though word exists in file
why is my code returning 0 even though word exists in file

Time:10-23

So this is a code of me trying to find a word a user inputs and look up how many lines contain the word and if no lines contain the word output not found however when i input a word that I know exist in the file it returns 0 and not only is the word in the file it doesn't even output not found like I want it to. (here is my code)

response = input('Please enter words: ')
letters = response.split()

count = 0

with open("alice.txt", "r", encoding="utf-8") as program:
    for line in program:
        if letters in line:
            count  = 1
            if(count < 1):
                print("not found")
print(count)

CodePudding user response:

What you're doing isn't gonna work the split function returns a list of strings and you're checking that list against a single string.

Is this what you wanted to do?

response = input("Please enter a word: ")
count = 0

with open("alice.txt", 'r') as program:
    for line in program:
        if response in line:
            count  = 1
    if count == 0:
        print("not found")

print(count)

CodePudding user response:

You dont need the split function and the place of if condition is wrong in your code. Please refer below code.

response = input('Please enter word: ')
count = 0

with open("alice.txt", "r", encoding="utf-8") as program:
    for line in program:
        if response in line:
            count  = 1

if count == 0:        
    print('Not found')
else:
    print(count)

CodePudding user response:

You had an issue with opening the txt file as a single line, and not as a list of the individual lines.

Adding ".readlines()" can fix this issue!

I also went ahead and set the individual lines as 'line', where I then search for the input word in the new 'line' variable.

response = input('Please enter words: ')
letters = response.split()


count = 0
foo = open(
     "alice.txt", "r",
     encoding="utf-8").readlines()


for line in foo:
    for word in letters:
        if word in line:
            count  = 1


if(count < 1):
    print("not found")
else:
    print(count)
  • Related