从python中的括号内提取数据

时间:2015-03-14 02:26:00

标签: python dictionary parentheses

我知道有很多同题的问题。我的情况有点不同。我有一个字符串:

"Cat(Money(8)Points(80)Friends(Online(0)Offline(8)Total(8)))Mouse(Money(10)Points(10000)Friends(Online(10)Offline(80)Total(90)))"

(请注意,括号嵌套在另一个内)

我需要将其解析为嵌套的词典,例如:

d["Cat"]["Money"] == 8
d["Cat"]["Points"] = 80
d["Mouse"]["Friends"]["Online"] == 10

等等。我想这样做没有库和正则表达式。如果您选择使用这些,请详细解释代码。 提前谢谢!

编辑:

虽然这段代码没有任何意义,但这是我到目前为止所做的:

o_str = "Jake(Money(8)Points(80)Friends(Online(0)Offline(8)Total(8)))Mouse(Money(10)Points(10000)Friends(Online(10)Offline(80)Total(90)))"
spl = o_str.split("(")
def reverseIndex(str1, str2):
    try:
        return len(str1) - str1.rindex(str2)
    except Exception:
        return len(str1)
def app(arr,end):
    new_arr = []
    for i in range(0,len(arr)):
        if i < len(arr)-1:
            new_arr.append(arr[i]+end)
        else:
            new_arr.append(arr[i])
    return new_arr

spl = app(spl,"(")
ends = []
end_words = []
op = 0
cl = 0
for i in range(0,len(spl)):
    print i
    cl += spl[i].count(")")
    op += 1
    if cl == op-1:
        ends.append(i)
        end_words.append(spl[i])
        #break
    print op
    print cl
    print
print end_words

结束语是每个语句开头的部分。我计划使用递归来完成剩下的工作。

1 个答案:

答案 0 :(得分:1)

现在 很有趣。你真的nerd-sniped我就这个......

def parse(tokens):
    """ take iterator of tokens, parse to dictionary or atom """
    dictionary = {}
    # iterate tokens...
    for token in tokens:
        if token == ")" or next(tokens) == ")":
            # token is ')' -> end of dict; next is ')' -> 'leaf'
            break
        # add sub-parse to dictionary
        dictionary[token] = parse(tokens)
    # return dict, if non-empty, else token
    return dictionary or int(token)

设置和演示:

>>> s = "Cat(Money(8)Points(80)Friends(Online(0)Offline(8)Total(8)))Mouse(Money(10)Points(10000)Friends(Online(10)Offline(80)Total(90)))"
>>> tokens = iter(s.replace("(", " ( ").replace(")", " ) ").split())
>>> pprint(parse(tokens))
{'Cat': {'Friends': {'Offline': 8, 'Online': 0, 'Total': 8},
         'Money': 8,
         'Points': 80},
 'Mouse': {'Friends': {'Offline': 80, 'Online': 10, 'Total': 90},
           'Money': 10,
           'Points': 10000}}

或者,您也可以使用一系列字符串替换将该字符串转换为实际的Python字典字符串,然后对其进行评估,例如:像这样:

as_dict = eval("{'" + s.replace(")", "'}, ")
                       .replace("(", "': {'")
                       .replace(", ", ", '")
                       .replace(", ''", "")[:-3] + "}")

这将包装&#39;叶子&#39;单例串中的字符串,例如{'8'}代替8,但这应该很容易在后处理步骤中修复。