1

我创建了一个解析器来从字符串中提取变量并用值填充它们,但是在检测字符串中的多个值时遇到了很多困难。让我举例说明:

以下消息包含变量“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'未检测到“OR”列表 ( ) 的第一个元素。我哪里错了?

编辑:我尝试更改属性 = ['mass', 'vel', 'OR', 'OR', 'AND'] 但这返回: {'OR': ['that new fangled thing'], 'OR': ['那个新奇的东西'],'vel':[18],'AND':['那个新东西'],'mass':[12.0]}

4

1 回答 1

0

您的 dict 理解{k.strip('-'): True if ... }会看到OR两次密钥,但第二次会覆盖第一次,因为 dict 只能包含一次密钥。

于 2018-10-29T19:33:58.063 回答