【问题标题】:Best way to parse complex configuration file解析复杂配置文件的最佳方法
【发布时间】:2015-03-05 17:02:38
【问题描述】:

我需要使用 Python 解析一个复杂的配置文件。我应该注意,这些文件的格式是我无法更改的,而是必须忍受的。

文件的基本结构是这样的:

Keyword1
"value1"
thisisirrelevantforkeyword1
Keyword2
"first", "second", "third"
1, 2, 3

Keyword3
2, "whatever"
firstparam, 1
secondparam, 2
again_not_relevant

最终,这个的输出应该是一个 JSON 字符串。

让我解释一下:

  • 每个关键字都有自己的规则。
  • 值在关键字后面的行中。
  • 例如,Keyword1 有一个值,即字符串value1value1 之后的行是无关紧要的。
  • 例如,Keyword2 有两个参数,第一个是字符串列表,第二个是整数列表。
  • 例如,Keyword3 具有可变数量的参数,由 Keyword3 之后第一行中的第一个整数表示。所以与Keyword3相关的参数是列表2,“whatever”,以及下面两行中的两个列表。

有一组固定的关键字,有自己的规则。当然,原则上我可以对整个事情进行硬编码,这会导致大量代码重复。另外,这对于新关键字或更改单个关键字的规则是非常不灵活的。

我宁愿准备一个包含所有关键字的 CSV 文件,以及它的定义规则,然后将其用作更通用的解析器函数的输入。

所以我的问题是: - 如何以简单的方式指定规则?我确信这有标准,但完全不知道从哪里开始寻找。 - 然后我如何使用这个语法来解析文件并生成我的 JSON?

我知道这是一件非常具体、特殊和复杂的事情;因此,我已经很感谢您指出正确方向的指针,因为我感到有些迷茫并且不确定从哪里开始寻找。

【问题讨论】:

  • 你至少应该尝试一下。使用有限状态机模型。对于每一行,如果它是关键字,则使用该关键字部分的解析例程。如果不是关键字,则传递给当前关键字部分的解析例程。让我们知道您的想法。

标签: python parsing grammar


【解决方案1】:

我认为您可以为您的选项设置一些具有非常特殊规则的类。

类似的东西:

class OptionBase(object):
    def __init__(self, name, **options):
        self.name = name
        self.raw_config_lines = []

    def parse_line(self, line):
        line = line.strip()
        if line:
            self.raw_config_lines.append(line)

    def get_config(self):
        raise Exception('Not Implemented')


class SimpleOption(OptionBase):
    def __init__(self, name, **options):
        super(SimpleOption, self).__init__(name, **options)
        self.expected_format = options.get('expected_format', str)

    def parse_line(self, line):
        if len(self.raw_config_lines):
            raise Exception('SimpleOption can only have one value')
        else:
            super(SimpleOption, self).parse_line(line)

    def get_config(self):
        return None if not self.raw_config_lines else self.expected_format(self.raw_config_lines[0])


class SomeComplexOption(OptionBase):
    def parse_line(self, line):
        #some special code which verify number of lines, type of args etc.

    def get_config(self):
        #some code to transform raw_line in another format

【讨论】:

    猜你喜欢
    • 2014-09-02
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    相关资源
    最近更新 更多