Reputation: 53
file1 = ...blahblahblah\nblah Lawyer Amy\nblahblah.... : want to print "Lawyer Amy"
file2 = ...\nblahblahblahblah Lawyer Amy(goverment)\nblahblah.... : want to print "Lawyer Amy(goverment)"
file3 = ...blah\nblahblahblah Lawyer Amy, Michael, Messi\nblahblah.... : want to print "Lawyer Amy, Michael, Messi"
so I need to print "Lawyer ~ before\n"
How can I solve this problem?
pseudo code:
f = open(file)
readline = f.readLine()
lawyer = re.findall("Laywer", readline)
print from lawyer till "\n"
Upvotes: 0
Views: 86
Reputation: 252
Here's a function that does what you want. It opens the file and start printing its lines. When a given keyword is contained in a line, it breaks the loop.
def print_until(file, keyword):
with open(file, 'r') as file:
for line in file.readlines():
print(line)
if keyword in line:
break
Upvotes: 0
Reputation: 521279
Here is a regex find all approach:
file2 = "\nblahblahblahblah Lawyer Amy(goverment)\nblahblah"
output = re.findall(r'\bLawyer[^\n]+', file2)
print(output) # ['Lawyer Amy(goverment)']
Upvotes: 1