Search code examples
pythonparagraphs

Python Count paragraph


Hello all so i've been tasked to count lines and paragraphs. Counting every line is obviously easy but im stuck on counting the paragraphs. If a paragraph has no character it will give back the number zero and for every paragraph is an increment higher. For example an input file is: Input and an Output should come out Output so my code is:

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

Solution

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