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
  How to remove unwanted images and tables from a Word file using Python? rownong 2 2,154 Feb-04-2025, 08:30 AM
Last Post: Pedroski55
  How to read a file as binary or hex "string" so that I can do regex search? tatahuft 3 2,848 Dec-19-2024, 11:57 AM
Last Post: snippsat
  Search in a file using regular expressions ADELE80 2 1,932 Dec-18-2024, 12:29 PM
Last Post: ADELE80
  Writing a Linear Search algorithm - malformed string representation Drone4four 10 5,976 Jan-10-2024, 08:39 AM
Last Post: gulshan212
  Search Excel File with a list of values huzzug 4 4,760 Nov-03-2023, 05:35 PM
Last Post: huzzug
  Replace a text/word in docx file using Python Devan 4 41,139 Oct-17-2023, 06:03 PM
Last Post: Devan
  Search for multiple unknown 3 (2) Byte combinations in a file. lastyle 7 4,417 Aug-14-2023, 02:28 AM
Last Post: deanhystad
  splitting file into multiple files by searching for string AlphaInc 2 4,157 Jul-01-2023, 10:35 PM
Last Post: Pedroski55
  search file by regex SamLiu 1 2,150 Feb-23-2023, 01:19 PM
Last Post: deanhystad
  If function is false search next file mattbatt84 2 2,491 Sep-04-2022, 01:56 PM
Last Post: deanhystad

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.