python: how to parse string of values like "a = 'abc' b = 'cde' c=13" -


basically if have string "a = 'abc' b = 'cde' c=13", how can parse dictionary like:

{'a': 'abc', 'b': 'cde', 'c': 13} 

note values can string literals or numbers, , string literals can contain equals signs themselves. spaces outside of string literals irrelevant, spaces inside must stay. string guaranteed alternate in key=value key=value key=value pattern though. special characters can , show inside string literals, keys plain alphabetical characters.

with pyparsing:

from pyparsing import word, suppress, charsnotin, nums, alphanums, dictof  int_value = word(nums) str_value = suppress("'") + charsnotin("'") + suppress("'") value = int_value | str_value identifier = word(alphanums) result = dictof(identifier + suppress("="), value)  pr = result.parsestring("a = 'abc' b = 'cde' c=13") print(pr.asdict())  # {'a': 'abc', 'b': 'cde', 'c': '13'} 

this not take escaped single quotes account, you'll have add that. there's documentation somewhere on pyparsing website.


Comments