2011-06-22 12 views
2

からリストと名前を交換してください。 ['a'、 'b'、 'x'、 'q'、 'w'、 'e'、 'y'、 'y'などの最終的な結果は、 z '、' c ']は、私はそのようなセクションに分割ようなファイルを持っているファイル

Aは、リストで辞書のファイルを埋める以下のコードを作成しましたが、私が挿入時に使用した順序ではありません(私はどこから始めるべきかわかりません)。

私も実際のリストから内容の「< sectionA」物事を交換するための最良の方法を知らない...

import re 
filename = input('Insert filename: ') 
f = open(filename) 
lines = f.readlines() 

elements = {} 
name = '' 

for i in lines: 
    if i[-1] == '\n': 
     i = i[:-1] 
    if not i: 
     continue 
    sec = re.findall(r'\[(\w+)\]', i) 
    if sec != []: 
     name = sec[0] 
     elements[name] = [] 
    else: 
     elements[name] += [i] 

print(elements) 

と結果は次のとおりです。 {「メイン」:[ 'A'、 'B'、 '< sectionA'、 'c']、 'sectionB':['q'、 'w'、 'e'] 'sectionA':['x'、 '< sectionB' 'y'、 'z']}

答えて

0

は、私はあなたのためにいくつかのクレイジーなコードを作りました:

import collections 
def load(fname): 
    d = collections.OrderedDict() 
    for i in (line.rstrip('\n') for line in open(fname) if line[:-1]): 
     d.update({i[1:-1]:[], '_':i[1:-1]}) \ 
     if i.startswith('[') else d[d['_']].append(i) 
    return d 

def join(first, dic): 
    f = dic[first] 
    for i,j in ((i,j[2:]) for i,j in enumerate(f) if j.startswith('<')): 
     f[i:i+1] = join(j, dic) 
    return f 

d = load('file.txt') 
join(next(iter(d)), d) 

join機能が右側のリストにコードを挿入して、2つの以上の場所で、必要に応じて複数回のリストを計算する必要はありません。 :)

OrderedDictを使用すると、常に正しいリストから開始します。

+0

私はあなたの結合機能が好きです。私はあなたのことを理解していなかったファイルcuzを読み込むために(いくつかの変更を加えて)私のコードでそれを使用します... –

0

それは難しいことではありません。これはアルゴリズムです:

1. Find all indexes in main starting with <. 
2. If none are found, go to 5. 
3. Replace every index with the according section (inserted unpacked). 
4. Go to 1. 
5. Done. 
0

私は2つの機能で問題を解決しました。 Pythonの辞書に入力ファイル(renderfile(filename))、および開始セクション(rendercontents(contents, startsection))とセクション参照して内容をマージするために第2のレンダリングのための第一:

def renderfile(filename): 
    contents = {} 
    with open(filename) as f: 
     currentsection = "" 
     for line in f.readlines(): 
      if line == "\n": 
       continue 
      line = line.replace("\n", "") 
      if line.startswith("["): 
       currentsection = line[1:-1] 
       contents[currentsection] = [] 
      else: 
       contents[currentsection].append(line) 
    return contents 

def rendercontents(contents, startsection): 
    returnlist = [] 
    for line in contents[startsection]: 
     if line.startswith("<"): 
      returnlist.extend(rendercontents(contents, line[2:])) 
     else: 
      returnlist.append(line) 
    return returnlist 

>>> newlist = rendercontents(renderfile("yourfile"), "main") 
>>> newlist 
['a', 'b', 'x', 'q', 'w', 'e', 'y', 'z', 'c'] 
+0

「ファイル」はどこに定義されていますか? –

+0

すみません。コードにいくつかの問題がありました。それを私が直した! – Pit

+2

私はOPがセクションが単一のファイルにあると言いました。セクション名のファイルを開こうとしています – JBernardo

関連する問題