Python Forum
Linear search/searching for a word in a file/list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Linear search/searching for a word in a file/list
#1
Guys, I have to make a program that and then asks user to input some word let's say (until user types STOP) and then checks if the word is in the list by linear search. And I can't use "in" operator here. This is so weird to me, can you give me some tips?
_________________________________
import sys

infile = open("ex5.acc", "r")

acc = ''
line = infile.readline()

while acc != "STOP":
   acc = input("Enter acc nr")
   line = infile.readline()
   if acc != line and acc != "STOP":
       print("It seems that there is no such accession nr in the file")
   elif acc == line:
       print("Accession number found")
print("Seems like you don;t want to search anymore")
Reply
#2
def check_word(word, text):
    words = text.split()
    for item in words:
        if item == word:
            return True
    return False

line = "It seems that there is no such accession nr in the file"
print(check_word('accession', line))
print(check_word('dog', line))
output:
Output:
True False
Reply
#3
Oh but you see. You used "in". And I can't do that. That's an exercise. :(
Reply
#4
def check_word(word, text):
    idx = 0
    words = text.split()
    while True:
        try:
            if word == words[idx]:
                return True
            idx += 1
        except IndexError:
            return False
 
line = "It seems that there is no such accession nr in the file"
print(check_word('accession', line))
print(check_word('dog', line))
Output:
True False
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  help with project of reading and searching big log file korenron 6 263 Jun-24-2021, 01:57 PM
Last Post: korenron
  Cloning a directory and using a .CSV file as a reference to search and replace bg25lam 2 329 May-31-2021, 07:00 AM
Last Post: bowlofred
  Trying to get the first letter of every word in a list DanielCook 2 518 Jan-05-2021, 05:06 PM
Last Post: deanhystad
  search for more than one word using lambda illmattic 2 549 Nov-13-2020, 11:44 AM
Last Post: illmattic
  Searching for specific word in text files. JellyCreeper6 1 504 Nov-03-2020, 01:52 PM
Last Post: DeaD_EyE
  Recognising mathematical expressions from word and pdf file Preeti15 0 503 Aug-19-2020, 09:06 AM
Last Post: Preeti15
  Trying to find first 2 letter word in a list of words Oldman45 7 1,051 Aug-11-2020, 08:59 AM
Last Post: Oldman45
  How to extract a single word from a text file buttercup 7 979 Jul-22-2020, 04:45 AM
Last Post: bowlofred
  Complex word search multiple files Kristenl2784 0 527 Jul-18-2020, 01:22 PM
Last Post: Kristenl2784
  Searching string in file and save next line dani8586 2 661 Jul-10-2020, 09:03 AM
Last Post: dani8586

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020