spookyblack spookyblack - 5 months ago 13
Python Question

Python: How to count average length of lines in a text file

I'm having trouble defining a function that takes a filename as a parameter and returns the average line length. Particularly having trouble removing the "\n" in the file.

This is what I have so far:

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

Answer

You can use strip() to remove preceding and trailing \n from the line and minor modification to your own code should be sufficient

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

This cleans out all leading and trailing whitespace. If you only want to strip out \n at the end of the line

(sum(len(line.replace("\n",'')) for line in lines) / len(lines))