我有一个文本文件,其中包含以下内容:
line1
text1
text2
text3
line2
something1
something2
我想创建另一个类似于以下内容的文本文件:
line1|text1|text2|text3
line2|something1|something2
我想要在文本文件中每当一行出现单词"line"时,将该行下面的所有行用竖杠(|)作为分隔符添加到那一行后面。我能在Python中实现吗?
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)
以下是一行代码,它使用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')]
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]
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)))