gpt4 book ai didi

Python 计数段落

转载 作者:太空狗 更新时间:2023-10-30 03:00:36 25 4
gpt4 key购买 nike

大家好,我的任务是统计行数和段落数。计算每一行显然很容易,但我坚持计算段落。如果一个段落没有字符,它将返回数字零,并且每个段落的增量都更高。例如输入文件是: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 计数段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28650454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com