以冒号分隔的分析

2024-06-11 13:11:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下文本块:

string = """
    apples: 20
    oranges: 30
    ripe: yes
    farmers:
            elmer fudd
                   lives in tv
            farmer ted
                   lives close
            farmer bill
                   lives far
    selling: yes
    veggies:
            carrots
            potatoes
    """

我试图找到一个好的正则表达式,它允许我解析出键值。我可以用类似的方法获取单行键值:

^{pr2}$

然而,当我打击农民或蔬菜时,问题就来了。在

使用重新标记,我需要做如下操作:

re.findall( '(.+?):\s(.+?)\n', string, re.S), 

然而,我花了不少时间去了解所有与农民相关的价值观。在

每个值后面有一个换行符,如果值是多行的,则在值之前有一个制表符或一系列制表符。在

我们的目标是要有这样的东西:

{ 'apples': 20, 'farmers': ['elmer fudd', 'farmer ted'] }

等等

提前谢谢你的帮助。在


Tags: 文本restring制表符yes键值农民ted
3条回答

您可能会看到PyYAML,如果不是有效的YAML,这个文本非常接近。在

这里有一个完全愚蠢的方法:

import collections


string = """
    apples: 20
    oranges: 30
    ripe: yes
    farmers:
            elmer fudd
                   lives in tv
            farmer ted
                   lives close
            farmer bill
                   lives far
    selling: yes
    veggies:
            carrots
            potatoes
    """


def funky_parse(inval):
    lines = inval.split("\n")
    items = collections.defaultdict(list)
    at_val = False
    key = ''
    val = ''
    last_indent = 0
    for j, line in enumerate(lines):
        indent = len(line) - len(line.lstrip())
        if j != 0 and at_val and indent > last_indent > 4:
            continue
        if j != 0 and ":" in line:
            if val:
                items[key].append(val.strip())
            at_val = False
            key = ''
        line = line.lstrip()
        for i, c in enumerate(line, 1):
            if at_val:
                val += c
            else:
                key += c
            if c == ':':
                at_val = True
            if i == len(line) and at_val and val:
                items[key].append(val.strip())
                val = ''
        last_indent = indent

    return items

print dict(funky_parse(string))

输出

^{pr2}$

下面是一个非常愚蠢的解析器,它考虑了(明显的)缩进规则:

def parse(s):
    d = {}
    lastkey = None
    for fullline in s:
        line = fullline.strip()
        if not line:
            pass
        elif ':' not in line:
            indent = len(fullline) - len(fullline.lstrip())
            if lastindent is None:
                lastindent = indent
            if lastindent == indent:
                lastval.append(line)
        else:
            if lastkey:
                d[lastkey] = lastval
                lastkey = None
            if line.endswith(':'):
                lastkey, lastval, lastindent = key, [], None
            else:
                key, _, value = line.partition(':')
                d[key] = value.strip()
    if lastkey:
        d[lastkey] = lastval
        lastkey = None
    return d

import pprint
pprint(parse(string.splitlines()))

输出为:

^{pr2}$

我认为这已经足够复杂了,作为一个显式的状态机,它看起来更干净,但是我想用任何新手都能理解的术语来编写它。在

相关问题 更多 >