我创建了一个解析器来从字符串中提取变量并用值填充它们,但是在检测字符串中的多个值时遇到很多困难。让我举例说明:
以下消息包含变量“mass”、“vel”、 bool 参数(或字符串)“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”列表的第一个元素(“这只是另一个描述符”
)。我哪里出错了?
编辑:我尝试更改属性 = ['mass', 'vel', 'OR', 'OR', 'AND'] 但这返回: {'OR': ['那个新的东西'], 'OR': ['那个新的东西'], 'vel': [18], 'AND': ['那个新的东西'], 'mass' :[12.0]}
最佳答案
你的字典理解 {k.strip('-'): True if ... }
看到 OR
键两次,但第二次覆盖第一次,如下所示一个字典只能包含一次键。
关于Python 自定义解析器未检测参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53051895/