蟒蛇;嵌套' \ t'解析

时间:2012-10-22 12:59:12

标签: python parsing

所以我试图将原始字符串解析成一个列表(实际上很多),所以让我说我有:

|[nothing detected] www.neopets.com/
        |status: (referer=http://www.google.com)saved 55189 bytes /fetch_d4cd213a56276ca726ddd437a1e75f1024ab7799
        |file: fetch_d4cd213a56276ca726ddd437a1e75f1024ab7799: 55189 bytes
        |file: decoding_367af53b4963986ecdeb9c09ce1a405b5b1ecd91: 68 bytes
        |[nothing detected] (script) images.neopets.com/js/common.js?v=6
            |status: (referer=http://www.google.com)saved 1523 bytes /fetch_8eeadcc08d4cb48c02dedf18648510b75190d1d7failure: [Errno 13] Permission denied: '/tmp/tmpsha1_8d7fb3ff1ef087c7ea2bf044dee294735a76ed4b.js'
            |file: fetch_8eeadcc08d4cb48c02dedf18648510b75190d1d7: 1523 bytes

它遵循类似的模式等等。让我们假设制表符的深度最多为3.我试图找到一种方法将其解析为每个子列表,因此在这种特殊情况下,它将是一个包含第一个“没有检测到”的列表,后面跟一个包含状态的列表,文件,文件和包含沿其状态/文件结果检测到的下一个内容的列表。 (我知道我的措辞不是最好的,对不起)。谢谢!

到目前为止,我已经尝试计算每行中的'\ t',并迭代整个事情,但我很困惑,因为我不能回到我的迭代中。

1 个答案:

答案 0 :(得分:1)

我认为你想要一个可以通过各种方式遍历的数据结构 - 即一个知道包含它的列表的列表 - 这是我的尝试:

s = """|[nothing detected] www.neopets.com/
\t|status: (referer=http://www.google.com)saved 55189 bytes /fetch_d4cd213a56276ca726ddd437a1e75f1024ab7799
\t\t|file: fetch_d4cd213a56276ca726ddd437a1e75f1024ab7799: 55189 bytes
\t\t|file: decoding_367af53b4963986ecdeb9c09ce1a405b5b1ecd91: 68 bytes
\t\t|[nothing detected] (script) images.neopets.com/js/common.js?v=6
\t\t\t|status: (referer=http://www.google.com)saved 1523 bytes /fetch_8eeadcc08d4cb48c02dedf18648510b75190d1d7failure: [Errno 13] Permission denied: '/tmp/tmpsha1_8d7fb3ff1ef087c7ea2bf044dee294735a76ed4b.js'
\t\t|file: fetch_8eeadcc08d4cb48c02dedf18648510b75190d1d7: 1523 bytes""".splitlines()

class MyList(list):
    def __init__(self, parent):
        self.parent = parent
        list.__init__(self)

top = current = MyList(None)
ntab_old = 0
for line in s:
    ntab = line.count('\t') #may need to be more robust to get tabs only at beginning
    if(ntab_old > ntab):
        #go up ntab_old - ntab levels.
        for _ in range(ntab_old - ntab):
            current = current.parent
    elif(ntab_old < ntab):
        #increased indentation means we want a new list
        current.append(MyList(current))
        current = current[-1]
    current.append(line)
    ntab_old = ntab

print top