Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
factorise split
#1
Hi

I've general question, not just linked with python (sorry if off topic)

i've a split expression which works:
reason.split(" ")[3].split("(")[2].split(")")[0].split("%")[0]

The expression I want to split is like:
test STATE (64/100)(64%) test1 test2.....

is there any mean to optimize it?

Thanks for help
Alex
Reply
#2
With information provided I don't see how it can be 'working'.

>>> reason = 'test STATE (64/100)(64%) test1 test2.....'
>>> reason.split(' ')[3]
'test1'


Next split on this string would be on ( which is not present, so there will be no split and as Python will be looking for item with indice 2 it will raise IndexError.

>>> _.split('(')
['test1']
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
Thanks !
In fact I want to find value 64 (from 64%) with my split


(Nov-02-2020, 01:41 PM)perfringo Wrote: With information provided I don't see how it can be 'working'.

>>> reason = 'test STATE (64/100)(64%) test1 test2.....'
>>> reason.split(' ')[3]
'test1'


Next split on this string would be on ( which is not present, so there will be no split and as Python will be looking for item with indice 2 it will raise IndexError.

>>> _.split('(')
['test1']
Reply
#4
With regex you can make it "simpler" :-D

import re

pattern = re.compile(r"(?P<name>\w+) (?P<state>\w+)\s+\((?P<progress>\d+)\/(?P<total>\d+)\)\((?P<percent>\d+)%\)")
line = "test STATE (64/100)(64%) test1 test2....."

match = pattern.search(line)
if match:
    print(match)
    print(match.group(0)) # All groups
    print(match.group(1)) # Group 1
    print(match.group(2)) # Group 2
    print(match.groupdict())
You can test regex here: https://regex101.com/
   

Keep in mind, that regex is not for everything good.
I added to the example also names for the groups: [inline=?P<name>][/inline]

If the rest test1 test2..... is also on the same line, then you need to extend the regex.
Just parse line by line.
enigma619 likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
Thanks for help !
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020