Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python split by character only if wrapped in parenthesis

I am parsing a large text file that has key value pairs separated by '='. I need to split these key value pairs into a dictionary. I was simply going to split by '='. However I noticed that some of the values contain the equals sign character. When a value contains the equals sign character, it seems to be always wrapped in parenthesis.

Question: How can I split by equals sign only when the equals sign is not in between two parenthesis?

Example data:

PowSup=PS1(type=Emerson,fw=v.03.05.00)

Desired output:

{'PowSup': 'PS1(type=Emerson,fw=v.03.05.00)'}

UPDATE: The data does not seem to have any nested parenthesis. (Hopefully that remains true in the future)

UPDATE 2: The key doesn't ever seem to have equals sign either.

UPDATE 3: The full requirements are much more complicated and at this point I am stuck so I have opened up a new question here: Python parse output of mixed format text file to key value pair dictionaries

like image 894
pengz Avatar asked Aug 07 '26 14:08

pengz


1 Answers

You could try partition('=') to split from the first instance

'PowSup=PS1(type=Emerson,fw=v.03.05.00)'.partition('=')[0:3:2]
like image 172
edyvedy13 Avatar answered Aug 09 '26 02:08

edyvedy13



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!