0

Is it possible to find line in file by part of it

As example:

I'm the good boy
I'm the bad boy
I'm the really good boy

Can i find the line by searching I'm the boy without writing good or bad

i need to catch the three lines

i tried

str = "iam good boy"
if "iam boy" in str:
    print ("yes")
else:
    print ("no") 

 
3
  • There are two lines. Which one do you want to find? Commented May 17, 2021 at 0:32
  • No, this won't work. in only works on exact substrings. Commented May 17, 2021 at 0:32
  • @BuddyBob i need to find both Commented May 17, 2021 at 0:37

3 Answers 3

1

Using RegEx, you can do something like this:

import re

strs = (
    "I'm the good boy",
    "I'm the good girl",
    "I'm the bad boy",
    "I'm the really good boy")
    
for s in strs:
    if re.match("I'm the .+ boy", s):
        print("Yes, it is, yeah")
    else:
        print("It's actually not")

prints

Yes, it is, yeah
It's actually not
Yes, it is, yeah
Yes, it is, yeah
Sign up to request clarification or add additional context in comments.

2 Comments

I have file with thousand of lines, is there anyway to find the lines withour specifying \\w+ because i don't know where exactly be the missing word ?
You can replace \\w+ with .+. I've updated my answer.
0

Here is what I found worked.

I had a text file, which had these two lines (which I understand you have):

I'm the good boy
I'm the bad boy

The I wrote this (with comments to explain how it works):

with open("testing.txt", 'r') as file:#Open the text file, do stuff and then close it when done
    row_counter = 0
    for row in file: #Go through each line in the file
        row_counter +=1
        if "I'm the" in row: #Check to see if a line in your file if it has "I'm the"
            if "boy" in row: #Narrows down to find a line that also contains "boy"
                print(f"Line {row_counter}") #In forms you which line(s) have "I'm the" and "boy" in them

The output is:

Line 1
Line 2

meaning both lines in the text file have "I'm the" and "boy" in them.

Comments

0

You can accomplish it using re.search to find the match. Also enumerate to keep the index and only return yes is all matches occur.

import re
stro = "iam good boy"
target = "iam boy"

def finder():
    for i,e in enumerate(target.split()):
        if re.search(e, stro):
            if  i == len(target.split()) - 1:
                return("yes")  
        else:
            return("no") 
  
finder()
# Yes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.