我必须编写一个带有两个参数的函数,infilename和outfilename。我必须从infilename中取出行并将新行写入outfilename。 infile是看起来像这样的文本。
My essay is kind of short. It
is only going to have a few inarticulate
lines and even
fewer paragraphs.
The second paragraph
has arrived, and you can see
it's not much.
The third paragraph now arrives
and departs as hastily.
我的目标是对行进行编号,使输出如下所示:
1, 1 My essay is kind of short. It
1, 2 is only going to have a few inarticulate
1, 3 lines and even
1, 4 fewer paragraphs.
0, 5
0, 6
0, 7
2, 8 The second paragraph
2, 9 has arrived, and you can see
2, 10 it's not much.
0, 11
0, 12
3, 13 The third paragraph now arrives
3, 14 and departs as hastily.
所以我需要跟踪段落的编号以及每个单独的行。我尝试了循环,但它们看起来并不富有成效。我在这个问题上取得的进展非常少。我非常擅长格式化,但我不确定如何跟踪它是什么段落或何时有多个'\ n'。任何帮助表示赞赏。
答案 0 :(得分:1)
with open("file.txt", "r") as f:
lines = f.readlines()
p = 1
for i, l in enumerate(lines):
if not l.strip():
print " {},{} {}".format(0,i+1,l)
if lines[i + 1].strip():
p += 1
else:
print " {},{} {}".format(p,i+1,l)
输出:
1,1 My essay is kind of short. It
1,2 is only going to have a few inarticulate
1,3 lines and even
1,4 fewer paragraphs.
0,5
0,6
0,7
2,8 The second paragraph
2,9 has arrived, and you can see
2,10 it's not much.
0,11
0,12
3,13 The third paragraph now arrives
3,14 and departs as hastily.
答案 1 :(得分:0)
希望我不只是做你的功课,但是你去了..
with open("example.txt") as f:
content = f.readlines()
line_count = 0
paragraph_count = 0
last_line = ""
for line in content:
line = line.strip()
if last_line == "" and len(line) > 1:
paragraph_count += 1
line_count += 1
last_line = line
print "[%d][%d] %s" % (line_count, paragraph_count, line)
答案 2 :(得分:0)
outfile = open('outfile.txt', 'w')
lastline = ""
linenum = 1
paranum = 1
with open('infile.txt') as infile:
lines = infile.readlines()
for line in lines:
if line != "\n" and lastline == "\n":
paranum += 1
if line != "\n":
newline = "%d, %-*d %s" % (paranum, len(str(len(lines))), linenum, line)
outfile.write(newline)
if line == "\n":
newline = "%d, %-*d %s" % (0, len(str(len(lines))), linenum, line)
outfile.write(newline)
lastline = line
linenum += 1