I created a parser to extract variables from strings and populate them with values, but am having a lot of difficulties detecting multiple values within a string. Let me illustrate:
The following message contains variables 'mass', 'vel', boolean arguments (or strings) 'AND', 'OR':
message = '"I have two variables" -mass "12" --vel "18" OR "this is just another descriptor" AND "that new thing" OR "that new fangled thing"'
With the above message the parser should detect and return a dictionary of variables containing values:
{'OR': ['this is just another descriptor', 'that new fangled thing'], 'vel': [18], 'AND': ['that new thing'], 'mass': [12.0]}
Here's the code:
import shlex
message = '"I have two variables" -mass "12" --vel "18" OR "this is just another descriptor" AND "that new thing" OR "that new fangled thing"'
args = shlex.split(message)
data = {}
attributes = ['mass', 'vel', 'OR', 'AND']
var_types = ['float', 'int', 'str', 'str']
for attribute in attributes: data[attribute] = []
for attribute, var_type in zip(attributes, var_types):
options = {k.strip('-'): True if v.startswith('-') else v
for k,v in zip(args, args[1:]+["--"]) if k.startswith('-') or k.startswith('')}
if (var_type == "int"):
data[attribute].append(int(options[attribute])) #Updates if "attribute" exists, else adds "attribute".
if (var_type == "str"):
data[attribute].append(str(options[attribute])) #Updates if "attribute" exists, else adds "attribute".
if (var_type == "float"):
data[attribute].append(float(options[attribute])) #Updates if "attribute" exists, else adds "attribute".
print(data)
The above code only returns the following dictionary:
{'OR': ['that new fangled thing'], 'vel': [18], 'AND': ['that new thing'], 'mass': [12.0]}
The first element of the 'OR' list ('this is just another descriptor'
) is not being detected. Where am I going wrong?
EDIT: I tried changing attributes = ['mass', 'vel', 'OR', ‘OR’, ‘AND'] but this returned: {'OR': ['that new fangled thing'], 'OR': ['that new fangled thing'], 'vel': [18], 'AND': ['that new thing'], 'mass': [12.0]}