1

I want to be able to manipulate the results of this regex and match it into groups so I can manipulate it. I get an error that says:

AttributeError: 'list' object has no attribute 'group'

My code is as follows:

sampleText= 'LOC OL85M132 LOC OL3M051'
matchLOC=re.findall(r'(LOC)\s([^\W\d_]{2})(\d+)M(\d{3})',sampleText)
for i in matchLOC:
     print(i)

My result with this is:

('LOC', 'OL', '85', '132')
('LOC', 'OL', '3', '051')

This is fine but when I try and assign the groups to variables like:

MP=matchLoc.group(2)
Yards=matchLoc.group(3)

I get that error above. I want to:

1) Assign the third group to a variable 'MP'

2) Assign the fourth group to variable 'Yards'

From here on I would then like to do a series of manipulations. eg add the digit 0 to the end of the last number and also if-else loops such as

if Yards >= 130:
   print('Yards = ' + str(int(Yards)-100))
   print('MP = ' + str(int(MP) + 0.5))

and so on.

2 Answers 2

1

Here is how you can do it with re.finditer:

import re
sampleText= 'LOC OL85M132 LOC OL3M051'
for m in re.finditer(r'(LOC)\s([^\W\d_]{2})(\d+)M(\d{3})',sampleText):
    #print (m.group(3) + " : " + m.group(4))
    MP = int(m.group(3))
    Yards = int(m.group(4))
    if Yards >= 130:
        print('Yards = ' + str(Yards-100))
        print('MP = ' + str(MP + 0.5))

See IDEONE demo

I have not modified your regex, but I see no point in capturing (LOC) since it is known text. Note that modifying the capturing groups, you will shift the group ids and you will need to revise the whole code. That's why I kept it as in the original code.

Sign up to request clarification or add additional context in comments.

3 Comments

Your solution only does it for one of them not both? I needed an output similar to eg LOC OL85M132 MP=X Yards=Y and then next line LOC OL3M051 MP=X Yards=Y. Thanks for the help by the way. Appreciate it (y)
In the second match, Yards < 130. Uncomment the commented line to see that the regex is working correctly.
Yeah man thanks. Ill test it out, but for the time being this seems good.
0

re.finall():

Return a list of all non-overlapping matches in the string.

you probably want :

for _, _, mp, yards in matchLOC:
    yards = int(yards)
    if yards >= 130:
       ...

3 Comments

But then I just get this AttributeError: 'tuple' object has no attribute 'group'
apologies - I mis-remembered the return format for findall() - does the updated answer do what you need?
Sorry could you just explain that. I'm just beginning out with python.

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.