How to parse multiple times in python
I'm trying to parse a string read from a txt file. The line is :
(0 ,3) :5.0|(1 ,3) : -5.0
I need to firstly get (0,3) then 5, after splitting with "|" I need to get (1,3) and -5
At the end, I should have 2 list variable that holds the values seperately. The first list should have : (0,3) and (1,3) The second list should hold : 5,-5
What I tried:
goal_states, their_reward = lines[5].split("|"), lines[5].rsplit(':', 1)
What I get : ['(0,3):5.0|(1,3)', '-5.0']
Thank you in advance
P.S: I shouldn't use any import statement.
Hope this is what you want.
s = "(0 ,3) :5.0|(1 ,3) : -5.0"
def get_result(s: str) -> tuple:
goals = []
rewards = []
for pair in s.split("|"):
goal, reward = pair.split(":")
goals.append(eval(goal.strip()))
rewards.append(float(reward.strip()))
return (goals, rewards)
print(get_result(s))
literal_eval
method that @Sayse used is of course the straight forward way of doing it. But if you want to do a little bit of parsing you can do:
txt = "(0 ,3) :5.0|(1 ,3) : -5.0"
txt = txt.replace(" ", "")
goal_states = []
their_rewards = []
for i in txt.split('|'): # ['(0,3):5.0', '(1,3):-5.0']
a, b = i.split(':')
_, n1, _, n2, _ = a # `a` is something like '(0,3)'
n1 = int(n1)
n2 = int(n2)
goal_states.append((n1, n2))
their_rewards.append(int(float(b)))
print(goal_states)
print(their_rewards)
output:
[(0, 3), (1, 3)]
[5, -5]