From a text file using Python 3.12, how do I extract substrings from lines that have multiple parentheses:
line1: 'group(something)'
line2: 'other(something) and group(something,something,something) and not group(something,something)'
I’m only interested in the ‘something’ ‘s from the ‘group()’ or ‘not group()’.
def find_within(search_in, search_for, until):
return search_in[search_in.find(search_for) + len(search_for) : search_in.find(until)]
group1 = find_within(line1, 'group(', ')') # extracting group from the first line
group2 = find_within(line2, 'and group(', ')') # extracting group from the second line
not_group = find_within(line2, 'not group(', ')') # extracting 'not group' from the second line
This function can handle extraction from lines that have only a single ‘group()’ like line1 but not the lines with multiple items like line2 (it would return null). I tried replacing the last .find()
by .rfind()
:
def find_within(search_in, search_for, until):
return search_in[search_in.find(search_for) + len(search_for) : search_in.rfind(until)]
But the output was:
‘something,something,something) and not group(something,something’
while I expect:
‘something,something,something’
.find()
looks for the first occurrence of the parenthesis, so when I’m seeking ‘something’ from ‘group(something)’ that is in the middle of the string, .find()
looks at the closing parenthesis from a pair ahead of ‘group(something)’, so returns ”. And .rfind()
looks for the last occurrence of the parenthesis so extracts everything until the last parenthesis.
Is there a better way with .find()
or do I need regular expressions?
1
I think the thing that you may be missing is that you can give str.find()
a second optional integer argument (str.find(target, offset)
) to tell where you want to start the search.
So in the example below we being with start = 0
for start of string
if we find the target string we advance start
by offset
to point to the character just past the ‘(‘ character. Then we search from that position forward to find the next ‘)’ character which is our stop
position
then the contents of the parentheses are just a slice from stop
to start
. In my example I then appended the contents
to a list
but you could print it out, or whatever you needed
eventually str.find()
will return -1 indicating there are no further matches so we return from the function
text = "group(a, b, c) and group(d, e, f) and not group(g, h, i)"
def findit(target, text):
"""look for target followed by (
save the text following the ( until the next )
append that text to results
when target doesn't match any more return results"""
results = []
target += '(' #add open parenthesis after target
offset = len(target)
start = 0
while True:
start = text.find(target, start)
#print(start)
if start == -1:
break
start += offset
stop = text.find(')', start)
contents = text[start:stop]
results.append(contents)
return results
print("ngroup")
print(findit('group', text))
print("nand group")
print(findit('and group', text))
print("nnot group")
print(findit('not group', text))
this program will produce this output:
group
['a, b, c', 'd, e, f', 'g, h, i']
and group
['d, e, f']
not group
['g, h, i']
1
You can use a pattern to find the expected outputs:
b(group)s*(([^)]+))|s*(bands+group)(([^)]+))|s*(bands+nots+group)(([^)]+))|s*b(other)(([^)]+))
Code:
import re
def _find(p, s):
return re.findall(p, s)
p = r'b(group)s*(([^)]+))|s*(bands+group)(([^)]+))|s*(bands+nots+group)(([^)]+))|s*b(other)(([^)]+))'
s = """
line1: 'group(something)'
line2: 'other(something) and group(something,something,something) and not group(something,something)'
I'
"""
print(_find(p, s))
Prints
[('group', 'something', '', '', '', '', '', ''), ('', '', '', '', '', '', 'other', 'something'), ('', '', 'and group', 'something,something,something', '', '', '', ''), ('', '', '', '', 'and not group', 'something,something', '', '')]
Notes
- There are 8 capture groups: four groups are the keys and four groups are the values.
(([^)]+))
: These four groups are the values.
Edit
You can use a simple pattern and get all the keys and values, and then proceed with your text processing tasks:
import re
def _find(p, s, as_dict=False):
matches = re.findall(p, s)
if as_dict:
return {m[0].strip(): m[1] for m in matches}
return matches
p = r"s*([^(']+)s*(([^)]+))"
s = """
line1: 'group(something)'
line2: 'other(something) and group(something,something,something) and not group(something,something)'
I'
"""
print(_find(p, s))
print(_find(p, s, as_dict=True))
Prints
[('group', 'something'), ('other', 'something'), ('and group', 'something,something,something'), ('and not group', 'something,something')]
{'group': 'something', 'other': 'something', 'and group': 'something,something,something', 'and not group': 'something,something'}
Details
The second pattern is pretty simple:
([^(']+)
: capture group 1 finds the keys.s*(([^)]+))
: capture group 2 finds the values.[^(']+
: means all the chars are allowed, except (i.e.,^
) these two[(']
, and then one or more times (i.e.,+
).([^)]+)
: means all chars are allowed, except (i.e.,^
) one char, that is the one,)
, in the character class (i.e.,[]
).
3