Python:如何计算文本文件中行的平均长度

时间:2016-06-17 03:41:39

标签: python

我在定义一个以文件名作为参数并返回平均线长的函数时遇到问题。特别是在删除文件中的“\ n”时遇到问题。

这是我到目前为止所做的:

    def averageLineLength(fn):
        fn = open("Ex_file.txt", "r")
        lines = fn.readlines()
        return (sum(len(line) for line in lines) / len(lines))

4 个答案:

答案 0 :(得分:2)

您可以使用app.post('/upload',function(req,res, next){ // what should go here to call the process res.writeHead(201, {'Content-type': 'text/plain'}); res.end("File uploaded."); } }); 从行中删除前导和尾随strip(),对您自己的代码进行微小修改就足够了

\n

清除所有前导和尾随空格。如果您只想在行尾删除\ n

   def averageLineLength(fn):
        fn = open("Ex_file.txt", "r")
        lines = fn.readlines()
        return sum([len(line.strip('\n')) for line in lines]) / len(lines)

答案 1 :(得分:0)

在python中摆脱空格(如换行符)的常用方法是strip。如果你想保留左侧,还有rstrip,如果你只是想要专门定位换行符,你可以给它们中的任何一个参数:

>>> '   Hello,    world  \n'.strip()
'Hello,    world'
>>> '   Hello,    world  \n'.rstrip()
'   Hello,    world'
>>> '   Hello,    world  \n'.strip('\n')
'   Hello,    world  '

另外两个注意事项:原始函数实际上并没有使用文件名,而在Python 2中它也执行整数除法(可能是也可能不是故意的)。通过这些修改:

def averageLineLength(fn):
    with open(fn) as f:
        lines = [line.strip() for line in f]
    return 1.0 * sum(map(len, lines)) / len(lines)

答案 2 :(得分:0)

您已经知道的是平均线长。

有一些不同的方法来处理删除' \ n'。

最简单的方法是使用" strip"方法。这将删除每一行的所有前导和尾随空格。

如果您只想删除结尾' \ n'。你可以写一个像这样的简单列表理解。

[l[:-1] if l[-1] == "\n" else l for l in lines]

或者只是删除最后一个字符而不检查,相信它是一个' \ n'因为你使用了" readlines"。

[l[:-1] for l in lines]

您还应该使用" with"文件上的构造块,以确保程序退出块时关闭。进行这些更改后,您的功能将变为:

def averageLineLength(fn):
    with open("Ex_file.txt", "r") as fn:
        lines = [l.strip() for l in fn.readlines()]
    return (sum(len(line) for line in lines) / len(lines)

或者,如果您想保留不是' \ n':

的前导和尾随空格
def averageLineLength(fn):
    with open("Ex_file.txt", "r") as fn:
        lines = [l[:-1] for l in fn.readlines()]
    return (sum(len(line) for line in lines) / len(lines)

答案 3 :(得分:0)

此解决方案也应解决问题:

def averageLineLength(fn):
    with open('Ex_file.txt".txt', 'r') as fn:
        lst = fn.readlines() 
        return sum([len(line.strip()) for line in lst]) / len(lst)