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
  Writing a Linear Search algorithm - malformed string representation Drone4four 10 836 Jan-10-2024, 08:39 AM
Last Post: gulshan212
  Search Excel File with a list of values huzzug 4 1,147 Nov-03-2023, 05:35 PM
Last Post: huzzug
  Replace a text/word in docx file using Python Devan 4 2,861 Oct-17-2023, 06:03 PM
Last Post: Devan
  Search for multiple unknown 3 (2) Byte combinations in a file. lastyle 7 1,257 Aug-14-2023, 02:28 AM
Last Post: deanhystad
  splitting file into multiple files by searching for string AlphaInc 2 816 Jul-01-2023, 10:35 PM
Last Post: Pedroski55
  search file by regex SamLiu 1 860 Feb-23-2023, 01:19 PM
Last Post: deanhystad
  If function is false search next file mattbatt84 2 1,111 Sep-04-2022, 01:56 PM
Last Post: deanhystad
  search a list or tuple for a specific type ot class Skaperen 8 1,855 Jul-22-2022, 10:29 PM
Last Post: Skaperen
  For Word, Count in List (Counts.Items()) new_coder_231013 6 2,500 Jul-21-2022, 02:51 PM
Last Post: new_coder_231013
  find some word in text list file and a bit change to them RolanRoll 3 1,482 Jun-27-2022, 01:36 AM
Last Post: RolanRoll

Forum Jump:

User Panel Messages

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