编程语言
首页 > 编程语言> > Python Count段落

Python Count段落

作者:互联网

大家好,所以我的任务是计算线条和段落.计算每一行显然很容易,但我坚持计算段落.如果一个段落没有字符,它将返回数字零,并且每个段落的增量更高.例如,输入文件是:Input,输出应该出现Output
所以我的代码是:

def insert_line_para_nums(infile, outfile):
    f = open(infile, 'r')
    out = open(outfile, 'w')
    linecount = 0
        for i in f:
            paragraphcount = 0
            if '\n' in i:
                linecount += 1
            if len(i) < 2: paragraphcount *= 0
            elif len(i) > 2: paragraphcount = paragraphcount + 1
            out.write('%-4d %4d %s' % (paragraphcount, linecount, i))
    f.close()
    out.close()

解决方法:

def insert_line_para_nums(infile, outfile):
    f = open(infile, 'r')
    out = open(outfile, 'w')
    linecount = 0
    paragraphcount = 0
    empty = True
    for i in f:
        if '\n' in i:
            linecount += 1
            if len(i) < 2:
                empty = True
            elif len(i) > 2 and empty is True:
                paragraphcount = paragraphcount + 1
                empty = False
            if empty is True:
                paragraphnumber = 0
            else:
                paragraphnumber = paragraphcount
        out.write('%-4d %4d %s' % (paragraphnumber, linecount, i))
    f.close()
    out.close()

标签:python,paragraphs
来源: https://codeday.me/bug/20190623/1275421.html