Reputation: 27
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")
Upvotes: 0
Views: 73
Reputation: 11521
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
Upvotes: 1
Reputation: 2729
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
Upvotes: 0
Reputation: 301
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.
Upvotes: 0