计算非空行以及python中这些行的长度之和 [英] counting non-empty lines and sum of lengths of those lines in python

查看:192
本文介绍了计算非空行以及python中这些行的长度之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Am试图创建一个接受文件名的函数,并返回一个2元组,其中包含该程序中非空行的数目以及所有这些行的长度之和.这是我当前的程序:

Am trying to create a function that takes a filename and it returns a 2-tuple with the number of the non-empty lines in that program, and the sum of the lengths of all those lines. Here is my current program:

def code_metric(file):
    with open(file, 'r') as f: 
        lines = len(list(filter(lambda x: x.strip(), f)))
        num_chars = sum(map(lambda l: len(re.sub('\s', '', l)), f))

    return(lines, num_chars)

我得到的结果是我得到的结果:

The result I get is get if I do:

if __name__=="__main__":
print(code_metric('cmtest.py'))

(3, 0)

何时应该:

(3,85)

还有使用函数映射,过滤和归约来找到线长总和的更好方法吗?我在上半部分做到了,但后半段却想不通. AM是python的新手,所以任何帮助都会很棒.

Also is there a better way of finding the sum of the length of lines using using the functionals map, filter, and reduce? I did it for the first part but couldn't figure out the second half. AM kinda new to python so any help would be great.

这是名为cmtest.py的测试文件:

Here is the test file called cmtest.py:

import prompt,math

x = prompt.for_int('Enter x')
print(x,'!=',math.factorial(x),sep='')

First line has 18 characters (including white space)
Second line has 29 characters
Third line has 38 characters

[(1, 18), (1, 29), (1, 38)]

行数为85个字符,包括空格.我很抱歉,我读错了问题.每行的总长度也应包括空格.

The line count is 85 characters including white spaces. I apologize, I mis-read the problem. The length total for each line should include the whitespaces as well.

推荐答案

一种相当简单的方法是构建一个生成器以剥离尾随空白,然后在其上enumerate(起始值为1)filter空行,并依次求和每行的长度,例如:

A fairly simple approach is to build a generator to strip trailing whitespace, then enumerate over that (with a start value of 1) filtering out blank lines, and summing the length of each line in turn, eg:

def code_metric(filename):
    line_count = char_count = 0
    with open(filename) as fin:
        stripped = (line.rstrip() for line in fin)
        for line_count, line in enumerate(filter(None, stripped), 1):
            char_count += len(line)
    return line_count, char_count

print(code_metric('cmtest.py'))
# (3, 85)

这篇关于计算非空行以及python中这些行的长度之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆