Python Forum
Searching for specific word in text files.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Searching for specific word in text files.
#1
How do I search in a file for a specific word? It should ignore word containing that word, for example.

word to search = 'ello'
text file -
hello
there
It shouldn't output anything file with the above text file
hello
ello
there
It should output 'success' with the above text file. How could I do this?
Reply
#2
my_string = "hello\nthere"
print(my_string)

start_index = my_string.find("ello")
print(start_index)

start_index = my_string.find("x")
print(start_index)
Opening files in text-mode for reading: https://docs.python.org/3/library/functions.html#open
Together with Context-Manager: https://realpython.com/working-with-file...as-pattern

All together in a function:

def has_pattern(file, pattern):
    with open(file, encoding="utf8") as fd:
        # inside this block the file is open for reading
        # read content -> find pattern -> return result_of_pattern != -1
        return fd.read().find(pattern) != -1
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to make a telegram bot respond to the specific word in a sentence? Metodolog 2 1,034 Dec-22-2020, 07:30 AM
Last Post: martabassof
  Split gps files based on time (text splitting) dervast 0 128 Nov-09-2020, 09:19 AM
Last Post: dervast
  Extracting data based on specific patterns in a text file K11 1 400 Aug-28-2020, 09:00 AM
Last Post: Gribouillis
  Find specific subdir, open files and find specific lines that are missing from a file tester_V 8 755 Aug-25-2020, 01:52 AM
Last Post: tester_V
  How to extract a single word from a text file buttercup 7 569 Jul-22-2020, 04:45 AM
Last Post: bowlofred
  Complex word search multiple files Kristenl2784 0 287 Jul-18-2020, 01:22 PM
Last Post: Kristenl2784
  Searching for a word Kristenl2784 0 294 Jul-09-2020, 01:06 AM
Last Post: Kristenl2784
  Outputting Sorted Text files Help charlieroberrts 1 331 Jul-05-2020, 08:37 PM
Last Post: menator01
  Read Multiples Text Files get specific lines based criteria zinho 5 679 May-19-2020, 12:30 PM
Last Post: zinho
  Making .exe file that requires access to text and html files ClassicalSoul 0 336 Apr-23-2020, 05:03 PM
Last Post: ClassicalSoul

Forum Jump:

User Panel Messages

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