Python中的段落编号

2024-05-18 10:52:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须编写一个包含两个参数的函数,infineName和outfilename。我必须从infineName中获取行并将新行写入outfilename。填充是这样的文本。在

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.

我的目标是对行进行编号,以便输出如下所示:

^{2}$

所以我需要记录段落的编号,以及每一行。我试过while循环,但似乎没有效果。我在这个问题上所取得的进展是微乎其微的。我很擅长格式化,但我不知道如何跟踪它是什么段落,或者当有多个'\n'时。感谢任何帮助。在


Tags: andofthe函数文本参数ismy
3条回答

希望我不只是做你的家庭作业,但给你。。在

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

输出:

^{pr2}$
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

相关问题 更多 >