2017-06-02 4 views
1

私はWikipediaページのセクション、サブセクション、サブサブセクションの階層構造を取得しようとしています。ページ名は「A」で、構造がPythonの文字列から階層構造を取得します

= b = 
= c = 
    == d == 
    == e == 
    === f === 
    === g === 
     ==== h ==== 
    === i === 
    == j == 
    == k == 
= l = 

兆候がセクションまたはサブの指標である平等に従っている。この場合

mystr = 'a = b = = c = == d == == e == === f === === g === ==== h ==== === i === == j == == k == = l =' 

私はこのような文字列を持っていますセクションなど。私はこれを行うことにより、その上のセクション、サブセクションを見つけることができたとしているこれまでのところ

mylist = ['a', 'a/b', 'a/c', 'a/c/d', 'a/c/e', 'a/c/e/f', 'a/c/e/g', 
      'a/c/e/g/h', 'a/c/e/i', 'a/c/j', 'a/c/k', 'a/l'] 

sections = re.findall(r' = (.*?)\ =', mystr) 
subsections = re.findall(r' == (.*?)\ ==', mystr) 
... 
私はこのようなすべてのリレーショナル階層構造を含むPythonのリストを取得する必要があります

しかし、私はここからどのように進んで目的のmylistを得るのか分かりません。最初の関数は、あなたの文字列を解析し、(0、 'A')のようなトークン(レベル、名前)、(1、 'B')を得
- - 二

+1

ようこそ。あなたの質問を改善するために、文字列(つまり等号の意味)とあなたが既に試みたことを示すポストコードから階層構造をどのように決定するべきかを記述してください。 –

+0

基本的に私はウィキペディアからテキストを抽出しようとしています。この文字列には、特定のウィキペディアページ(セクション、サブセクション、サブサブセクションなど)のコンテンツ名が含まれます。私の例では、aはページ名です。 b、c、lはセクションです(したがって、それらの周りには等号が1つしかありません)。 d、e、jはcの下のサブセクションである(したがって、それらの周りに2つの等号がある)。 – user8101320

答えて

0

あなたはこのようにそれを行うことができます一つはそこから木を造る。

import re 

def tokens(string): 
    # The root name doesn't respect the '= name =' convention, 
    # so we cut the string on the first " = " and yield the root name 
    root_end = string.index(' = ') 
    root, rest = string[:root_end], string[root_end:] 
    yield 0, root 

    # We use a regex for the next tokens, who consist of the following groups: 
    # - any number of "=" followed by 0 or more spaces, 
    # - the name, not containing any = 
    # - and again, the first group of "=..." 

    tokens_re = re.compile(r'(=+ ?)([^=]+)\1') 
    # findall will return a list: 
    # [('= ', 'b '), ('= ', 'c '), ('== ', 'd '), ('== ', 'e '), ('=== ', 'f '), ...] 
    for token in tokens_re.findall(rest): 
     level = token[0].count('=') 
     name = token[1].strip() 
     yield level, name 


def tree(token_list):  
    out = [] 
    # We keep track of the current position in the hierarchy: 
    hierarchy = [] 
    for token in token_list: 
     level, name = token 
     # We cut the hierarchy below the level of our token 
     hierarchy = hierarchy[:level] 
     # and append the current one 
     hierarchy.append(name) 
     out.append('/'.join(hierarchy)) 
    return out 


mystr = 'a = b = = c = == d == == e == === f === === g === ==== h ==== === i === == j == == k == = l =' 
out = tree(tokens(mystr)) 
# Check that this is your expected output 
assert out == ['a', 'a/b', 'a/c', 'a/c/d', 'a/c/e', 'a/c/e/f', 'a/c/e/g', 
      'a/c/e/g/h', 'a/c/e/i', 'a/c/j', 'a/c/k', 'a/l'] 

print(out) 
# ['a', 'a/b', 'a/c', 'a/c/d', 'a/c/e', 'a/c/e/f', 'a/c/e/g', 'a/c/e/g/h', 'a/c/e/i', 'a/c/j', 'a/c/k', 'a/l'] 
関連する問題