AliCa
AliCa

Reputation: 279

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.

Upvotes: 2

Views: 385

Answers (5)

S.B
S.B

Reputation: 16564

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]

Upvotes: 2

Murad Eliyev
Murad Eliyev

Reputation: 120

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))

Upvotes: 2

Jimi Österholm
Jimi Österholm

Reputation: 56

This can be achieved with list comprehension:

For example:

string = "(0, 3): 5.0|(1 ,3) : -5-0"
parsed_list1, parsed_list2 = [i.split(":") for i in string.split("|")]

print(parsed_list1)
print(parsed_list2)

Output:

['(0, 3)', ' 5.0']

['(1 ,3) ', ' -5-0']

Upvotes: 1

AliCa
AliCa

Reputation: 279

I have solved this performing multiple split operation.

goal_states=[]
their_obstacles=[]
for i in "(0 ,3) :5.0|(1 ,3) : -5.0".split("|"):
   goal_states.append(i.split(":")[0])
   their_obstacles.append(i.split(":")[1])

Upvotes: 0

Sayse
Sayse

Reputation: 43330

You can convert the pipe to a comma, then format it as a dictionary and use ast's literal_eval to give yourself a dictionary to work with

  import ast
  s = "(0 ,3) :5.0|(1 ,3) : -5.0"
  s = s.replace("|", ",")
  ast.literal_eval(f"{{{s}}}")
{(0, 3): 5.0, (1, 3): -5.0}

Upvotes: 1

Related Questions