Python正则表达式挑战缩进

时间:2012-06-28 11:59:31

标签: python regex regex-negation

尝试解决一个问题,我知道我可以通过遍历字符串来解决但是使用python我确信有一个正则表达式可以更优雅地解决它...感觉就像放弃求助于迭代过程!

基本上我在属性的单个单元格中有一个列表,我需要确定哪些属性是子属性,哪些是子属性,并将它们与它们所属的属性相匹配。例如:

ID = 11669 Antam红土镍/镍铁操作     
ID = 19807 Gebe红土镍矿号(ID = 19808)Gee Island红土镍矿号ID = 18923 Mornopo红土镍矿号ID = 29411 Pomalaa Ferronickel冶炼厂
ID = 19806 Pomalaa红土镍矿号ID = 29412 Maniang红土镍项目
ID = 11665东南苏拉威西红土镍项目
ID = 27877 Bahubulu红土镍矿床

应该生成:

MasterProp,    SubProp
11669,          19807
11669,          19808
11669,          18923
11669,          29411
11669,          19806
19806,          29412
11669,          11665
11665,          27877

获得11669和第二级很容易 - 只需抓住我找到的第一个ID,然后添加到所有其他ID。但是获得“第三级”要困难得多

我尝试了以下

tags = re.compile('ID=(\d+).+(\&nbsp\;){8}')                        
for tag, space in tags.findall(str(cell)): 
    print tag

但是这给了我8个空格之前的第一个ID而不是8个空格之前的最后一个ID ...所以在上面的例子中我得到11669而不是19806。我怀疑有一个表达式,我可以说,找到一个ID=(\d+),其中没有其他ID=(\d+)在它和8个空格之间,但这证明超出了我的(新手)能力!任何帮助都会受到欢迎......

2 个答案:

答案 0 :(得分:1)

使用BS获取标签后,您希望这样做:

>>> from urlparse import urlparse, parse_qs
>>> myurl = 'ShowProp.asp?LL=PS&ID=19807'
>>> parse_qs(urlparse(myurl).query)
{'LL': ['PS'], 'ID': ['19807']}
>>> parse_qs(urlparse(myurl).query)['ID']
['19807']
>>> 

答案 1 :(得分:0)

我认为使用HTML的示例代码更有意义 - 实际数据,而不是挥手。

bs = BeautifulSoup.BeautifulSoup(html)

parent_stack = [None]
res = []
for span in bs.findAll('span', {'style':'white-space:nowrap;display:inline-block'}):
    indent = 1 + span.previousSibling.count(' ') / 5
    id = int(span.find('input')['value'])
    name = span.find('a').text.strip()

    # warning! this assumes that indent-level only ever
    #   increases by 1 level at a time!
    parent_stack = parent_stack[:indent] + [id]
    res.append(parent_stack[-2:])

结果

[[None, 11669],
 [11669, 19807],
 [11669, 19808],
 [11669, 18923],
 [11669, 29411],
 [11669, 19806],
 [19806, 29412],
 [11669, 11665],
 [11665, 27877],
 [11665, 50713],
 [11665, 27879],
 [11665, 27878],
 [11669, 11394]]