4

こんにちは、私は行と段落を数え​​ることを任されています。すべての行を数えるのは明らかに簡単ですが、段落を数え​​ることに固執しています。段落に文字が含まれていない場合、数字のゼロが返され、段落ごとに増分が高くなります。たとえば、入力ファイルは次のとおりです。入力と出力が出力されるはずな ので、私のコードは次のとおりです。

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

2 に答える 2

2
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()
于 2015-02-21T20:37:41.040 に答える
2

これは 1 つの方法であり、最も美しい方法ではありません。

import re
f = open('a.txt', 'r')

paragraph = 0

lines = f.readlines()

for idx, line in enumerate(lines):
    if not line == '\n':
        m = re.search(r'\w', line)
        str = m.group(0)

    try:
        # if the line is a newline, and the previous line has a str in it, then  
        # count it as a paragraph.
        if line == '\n' and str in lines[idx-1]: 
            paragraph +=1
    except:
        pass

if lines[-1] != '\n': # if the last line is not a new line, count a paragraph.
    paragraph +=1

print paragraph
于 2015-02-21T20:37:50.860 に答える