Python 自定义解析器未检测参数

标签 python shlex

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

以下消息包含变量“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/

相关文章:

python - 为什么 python string cut 在请求 12 个符号时返回 11 个符号?

python 子进程模块在执行批处理文件时卡住

python - 从 pandas Dataframe 中删除重复数据

Python shlex.split(),忽略单引号

python - 如何在 Windows 上引用路径? (类似于 shlex.quote)

python - 如何在 Python 中按值对字典进行排序?

python - 在向量化操作中调用 numpy 函数会影响性能吗?

python - 使用 shlex 拆分多行字符串并保留引号字符

Python:拆分字符串,尊重并保留引号