以下是我要做的事情: 我试图解决与包装文本文件有关的问题。
我想打开一个txt文件,读取一行,如果该行包含我想要包含的内容,请检查下一行,看它是否包含第一行中的内容。如果没有,请将该行添加到第一行。
import re
stuff = open("my file")
for line in stuff:
if re.search("From ", line):
first = line
print first
if re.search('From ', handle.next()):
continue
else: first = first + handle.next()
else: continue
我看了很多东西,似乎无法找到答案。请帮忙!
答案 0 :(得分:0)
我会尝试做这样的事情,但这对于“From”的三元组来说是无效的,而且根本不优雅。
lines = open("file", 'r').readlines()
lines2 = open("file2", 'w')
counter_list=[]
last_from = 0
for counter, line in enumerate(lines):
if "From " in line and counter != last_from +1:
last_from = counter
current_count = counter
if current_count+1 == counter:
if "From " in line:
counter_list.append(current_count+1)
for counter, line in enumerate(lines):
if counter in counter_list:
lines2.write(line)
else:
lines2.write(line, '\n')
如果有帮助,你可以查看第2行。
您还可以恢复行的顺序,然后检查下一行而不是之前的行。这将在一个循环中解决您的问题。
答案 1 :(得分:0)
感谢Martjin帮助我重置我的思维框架!这就是我想出的:
handle = open("my file")
first = ""
second = ""
sent = ""
for line in handle:
line = line.rstrip()
if len(first) > 0:
if line.startswith("From "):
if len(sent) > 0:
print sent
else: continue
first = line
second = ""
else:
second = second + line
else:
if line.startswith("From "):
first = line
sent = first + second
这可能很粗糙,但它确实完成了工作!