我创建了一个解析器来从字符串中提取变量并用值填充它们,但在检测字符串中的多个值时遇到了很多困难。让我举例说明:
以下消息包含变量"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]}
未检测到"OR"列表('this is just another descriptor'
(的第一个元素。我哪里错了?
EDIT:我尝试更改attributes=['mass','level','OR','OR','AND'],但返回:{'OR':[有尖牙的新事物],'OR';[有尖齿的新事物'],'vel':[18],'AND':[新事物'','mass':[12.0]}
您的dict理解{k.strip('-'): True if ... }
会看到OR
键两次,但第二次会覆盖第一次,因为dict只能包含一次键。