用文件中的列表替换名称

时间:2011-06-22 21:40:14

标签: python list file dictionary

我有一个像这样的部分分开的文件:

[main]

a
b
< sectionA
c

[sectionA]
x
< sectionB
y
z

[sectionB]
q
w
e

我想用“A”中的内容替换“&lt; sectionA”,依此类推。最终结果应该是一个列表,其中只包含正确顺序的元素,如下所示: ['a','b','x','q','w','e','y','z','c']

使下面的代码用字典填充文件中的列表,但顺序不是我在插入中使用的顺序(所以我无法确定从哪里开始)。

我也不知道用实际列表中的内容替换“&lt; 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)

结果是: {'main':['a','b','&lt; sectionA','c'],'sectionB':['q','w','e'],'sectionA':['x','&lt; sectionB','y','z']}

3 个答案:

答案 0 :(得分: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.

答案 1 :(得分:0)

我用两个函数解决了你的问题。第一个用于将输入文件(renderfile(filename))呈现为Python字典,第二个用于将内容与带有起始部分(rendercontents(contents, startsection))的section-references合并:

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']

答案 2 :(得分: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函数在右侧列表中插入代码时,如果需要在两个或多个位置,则不必多次计算列表。 :)

使用OrderedDict,您总是从正确的列表开始。