2011-04-26 68 views

回答

4

如果你的文件是不是非常大

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
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))) 
4

這裏是一個一行它採用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')] 
+0

+1因爲這是唯一提供的一線答案 – 2011-04-26 14:17:41

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] 
相關問題