我创建了一个解析器,用于从字符串中提取变量并为其填充值,但是在检测字符串中的多个值时遇到很多困难。让我举例说明:
以下消息包含变量'mass','vel',布尔参数(或字符串)'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"'
使用以上消息,解析器应检测并返回包含值的变量字典:
{'OR': ['this is just another descriptor', 'that new fangled thing'], 'vel': [18], 'AND': ['that new thing'], 'mass': [12.0]}
代码如下:
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)
上面的代码仅返回以下字典:
{'OR': ['that new fangled thing'], 'vel': [18], 'AND': ['that new thing'], 'mass': [12.0]}
未检测到“或”列表('this is just another descriptor'
)的第一个元素。我要去哪里错了?
编辑:我尝试更改属性= ['mass','vel','OR','OR','AND'],但这返回了: {'OR':['那新的东西”,'OR':['那新的东西”],'vel':[18],'AND':['那新东西”],'质量' :[12.0]}
答案 0 :(得分:0)
您的字典理解{k.strip('-'): True if ... }
两次看到OR
键,但是第二个覆盖了第一个,因为字典只能包含一个键。