【问题标题】:Coding a parser in Python [closed]用 Python 编写解析器 [关闭]
【发布时间】:2023-03-08 04:05:02
【问题描述】:

我正在尝试用 Python 制作一个配置阅读器。该配置具有以下结构:

@section:
    property = 'value'
end

@section2:
    property2 = 'value'
end

使用两个函数管理配置:

getValue(file, section, property)
setValue(file, section, property, newvalue)

但我不知道如何做解析器。请帮忙:\

【问题讨论】:

  • 这将被关闭,因为你没有任何代码。请阅读帮助文件。
  • 这两个函数是怎么定义的?它几乎决定了您的解析器需要做什么。

标签: python parsing config


【解决方案1】:

这很有趣。这应该可以完美地工作。我不确定是否要去掉值旁边的单引号,但我决定去掉它们以保证输出的简洁。

with open('configfile.cfg') as f:
    data = f.readlines()

    config = {}
    current_section = None
    for line in data:
        line = line.strip()
        if line == 'end' or not line:
            continue

        if line.startswith('@'):
            current_section = line[1:-1]
            config[current_section] = {}
        else:
            key, value = line.split('=')
            config[current_section][key.strip()] = value.strip().strip("'")

    print(config)

为了将来的参考,如果您提供少量实际数据然后描述数据,而不是提供类型名称,那么提供帮助会容易得多。例如,我将其用作配置文件:

@section:
    red = '3three'
end

@section2:
    blue = '4four'
    green = '5five'
end

这是该配置文件的输出字典:

{'section': {'red': '3three'}, 'section2': {'blue': '4four', 'green': '5five'}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-14
    • 2011-08-17
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    相关资源
    最近更新 更多