如何在Python中使用分隔符将多行文本组合成一行来分隔它们?

时间:2011-04-26 14:09:14

标签: python text

我在文本文件中有以下内容:

line1
text1
text2
text3
line2
something1
something2

我想创建另一个看起来像这样的文本文件:

line1|text1|text2|text3
line2|something1|something2

每当文本文件中的一行显示“line”时,我想将其下面的每一行添加到该行中,并带有“|”分隔符。我可以用Python做到这一点吗?

4 个答案:

答案 0 :(得分:6)

如果您的文件不是非常大

data=open("file").readlines()
for n,line in enumerate(data):
    if line.startswith("line"):
       data[n] = "\n"+line.rstrip()
    else:
       data[n]=line.rstrip()
print '|'.join(data)

答案 1 :(得分:3)

这是一个使用line1, line2, ...而不实际读取该行数字的单行:

['|'.join(['line%d' % i] + x.strip('\n').split('\n')) for i, x in enumerate(re.split('line[0-9]+', l)) if x.strip('\n')]

答案 2 :(得分:2)

def join_lines(lines, sent='line'):
    current = []
    for line in lines:
        if line.startswith(sent):
            yield current
            current = []

        current.append(line)
    yield current

# data = open('input.txt', 'rt')
data = """line1
text1
text2
text3
line2
something1
something2""".splitlines()

print ['|'.join(line) for line in join_lines(data) if line]

答案 3 :(得分:1)

current = None 
parts = [] 
with open('input', 'rb') as f:
    for line in f:
        if line.startswith('line'):
            current = [line.strip()]
            parts.append(current)
        elif current is not None:
            current.append(line.strip())

with open('output', 'w+b') as f:
    f.write('\n'.join(('|'.join(part) for part in parts)))