有一个如下文件:
bash-4.1$ cat sample.txt
22|Data Structures|45
23|English|52
22|English|Level 2|51
26|Data Structures
23|Data Structures|61
26|English|81
23|English|52
21|English|5
23|English|52
bash-4.1$
以上文件需要在空白处反转,并输出如下:
bash-4.1$ cat reversed_sample.txt
22|English|Level 2|51
23|English|52
22|Data Structures|45
26|English|81
23|Data Structures|61
26|Data Structures
23|English|52
23|English|52
21|English|5
bash-4.1$
这如何在python中完成?
我试图识别空行和非空行:
count=0
fp=open("sample.txt")
blank=[]
full_line=[]
count=0
for line in fp:
count=count+1
x=line.strip()
if (len(x)==0):
blank.append(count)
else:
full_line.append(count)
print blank
print full_line
fp.close()
答案 0 :(得分:2)
这里是GNU awk中的一个:
$ awk -F'\n' -v RS='' '{for(i=NF;i>=1;i--)print $i;print ""}' file
22|English|Level 2|51
23|English|52
22|Data Structures|45
26|English|81
23|Data Structures|61
26|Data Structures
23|English|52
23|English|52
21|English|5
答案 1 :(得分:1)
您可以使用itertools.groupby
:
from itertools import groupby
with open('sample.txt') as f:
print(''.join(''.join(list(g)[::-1]) for _, g in groupby(f, key='\n'.__eq__)))
使用示例输入,将输出:
22|English|Level 2|51
23|English|52
22|Data Structures|45
26|English|81
23|Data Structures|61
26|Data Structures
23|English|52
23|English|52
21|English|5
答案 2 :(得分:1)
尝试使用此简单的sed
命令
sed -n '/^$/{x;p;d};G;h;$s/\n$//p' filename
输出:
22|English|Level 2|51
23|English|52
22|Data Structures|45
26|English|81
23|Data Structures|61
26|Data Structures
23|English|52
23|English|52
21|English|5
答案 3 :(得分:0)
您可以这样做。
with open("sample.txt", 'r') as f1:
with open("sampleOut.txt", 'w') as f2:
lineStack = []
for l in f1: # point 1
print l
if not l.strip():
while (len(lineStack) > 0):
f2.write(lineStack.pop())
f2.write("\n")
else:
lineStack.append(l)
i = 0
while (len(lineStack) > 0): # point 3
f2.write(lineStack.pop())
if (i == 0) :
f2.write("\n") # point 2
i = i + 1;
注意事项:
not l.strip()
。for l in f1:
的末尾,您可能仍会留下非空堆栈。因此,不要忘记将其内容刷新到文件中。