Python - 解析配置文件 - 流控制

时间:2016-08-09 18:24:46

标签: python python-2.7

我正在尝试编写一个python 2.7脚本来解析配置文件。配置文件具有标准设置,但并未填充所有设置。我已经能够提取单个部分的值,但是当我添加其他条目时,我的脚本逻辑失败了。我想我可以在配置文件中使用属性(RuleName,Next)来打破思考,但我想不出如何实现这一点。下面是配置的示例。

配置文件

    RuleName "Rule 1"
    value1 = "some value"
    value2 = "some value"
    value3 = "some value"
    value4 = "some value"
Next
RuleName = "Rule 2"
    value1 = "some value"
    value2 = "some value"
    value3 = "some value"
Next
RuleName = "Rule 3"
    value1 = "some value"
    value2 = "some value"
    value3 = "some value"
    value4 = "some value"
    value5 = "some value"
Next

这是我的脚本的逻辑。任何的意见都将会有帮助。这是我第一次尝试用Python编写更复杂的脚本。我确信有更复杂的方法来达到这个目的但是我想在学习python的时候保持相对基础。

谢谢!

for line in lines:
    n = line.lstrip()
    if n.find(rulesetting1) != -1:
        pos = len(rulesetting1)
        rulevalue1 = n[pos:]
    elif n.find(rulesetting2) != -1:
        pos = len(rulesetting2)
        rulevalue2 = n[pos:]
    elif n.find(rulesetting3) != -1:
        pos = len(rulesetting3)
        rulevalue3 = n[pos:]
    elif n.find(rulesetting4) != -1:
        pos = len(rulesetting4)
        rulevalue4 = n[pos:]
    elif n.find(rulesetting5) != -1:
        pos = len(rulesetting5)
        rulevalue5 = n[pos:]
    elif n.find("Next") != -1:
        Start cycle over?

如何搜索“下一步”然后开始循环。最终我想将其写入CSV文件,但我需要先将此流程写下来。

2 个答案:

答案 0 :(得分:0)

这对我来说就像是一本字典。

optionsdict = dict()

curkey = None
for line in optionsfile:
    if line.strip().startswith("RuleName"):
        curkey = line.split("=")[1].strip()  # whatever's after the =
    elif line.strip() == "Next":
        pass  # not sure what you're doing with the Next lines...
    else:
        option, value = map(str.strip, line.split("="))
        optionsdict.setdefault(curkey, {})[option] = value

也就是说,如果您正在全力以赴地使用包含电池的更标准格式,似乎更容易。

# configfile.ini
[Rule 1]
value1 = "some value"
value2 = "some value"
value3 = "some value"
value4 = "some value"
[Rule 2]
value1 = "some value"
value2 = "some value"
value3 = "some value"
value4 = "some value"
[Rule 3]
value1 = "some value"
value2 = "some value"
value3 = "some value"
value4 = "some value"
value5 = "some value"

# Python script

from configparser import ConfigParser

config = ConfigParser()
config.read_file("path/to/configfile.ini")
config["Rule 1"]["value1"]  # "some value"

这使用configparser包来解析您的选项。

答案 1 :(得分:0)

发现了这个老问题,对该问题的另一种解决方案是使用TTP来解析上面的文本,下面是代码:

from ttp import ttp
template = """
<input load="text">
Next
RuleName = "Rule 2"
    value1 = "some value"
    value2 = "some value"
    value3 = "some value"
Next
RuleName = "Rule 3"
    value1 = "some value"
    value2 = "some value"
    value3 = "some value"
    value4 = "some value"
    value5 = "some value"
</input>

<group name="{{ rule_name }}">
RuleName = "{{ rule_name | ORPHRASE }}"
<group name="data">
    {{ key }} = "{{ value | ORPHRASE }}"
</group>
</group>
"""

parser = ttp(template=template)
parser.parse()
print(parser.result(format="json")[0])

上面的代码将打印:

[
    {
        "Rule 2": {
            "data": [
                {
                    "key": "value1",
                    "value": "some value"
                },
                {
                    "key": "value2",
                    "value": "some value"
                },
                {
                    "key": "value3",
                    "value": "some value"
                }
            ]
        },
        "Rule 3": {
            "data": [
                {
                    "key": "value1",
                    "value": "some value"
                },
                {
                    "key": "value2",
                    "value": "some value"
                },
                {
                    "key": "value3",
                    "value": "some value"
                },
                {
                    "key": "value4",
                    "value": "some value"
                },
                {
                    "key": "value5",
                    "value": "some value"
                }
            ]
        }
    }
]