0

我有以下文本块:

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
    """

我正在尝试找到一个好的正则表达式,它可以让我解析出键值。我可以通过以下方式获取单行键值:

'(.+?):\s(.+?)\n'

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

使用 re 标志,我需要执行以下操作:

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

然而,我有一段时间抓住与农民相关的所有价值观。

每个值后面都有一个换行符,当它们是多行时,值之前有一个制表符或一系列制表符。

目标是拥有类似的东西:

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

等等

预先感谢您的帮助。

4

3 回答 3

2

您可能会查看PyYAML,如果不是真正有效的 YAML,此文本非常接近。

于 2013-10-15T22:46:43.143 回答
1

这是一种完全愚蠢的方法:

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))

输出

{'farmers:': ['elmer fudd', 'farmer ted', 'farmer bill'], 'apples:': ['20'], 'veggies:': ['carrots', 'potatoes'], 'ripe:': ['yes'], 'oranges:': ['30'], 'selling:': ['yes']}
于 2013-10-15T23:16:15.207 回答
1

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

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()))

输出是:

{'apples': '20',
 'oranges': '30',
 'ripe': ['elmer fudd', 'farmer ted', 'farmer bill'],
 'selling': ['carrots', 'potatoes']}

我认为这已经足够复杂,以至于它看起来像显式状态机一样干净,但我想用任何新手都能理解的方式来写这个。

于 2013-10-15T23:37:44.637 回答