Hello I am supposed to find a bunch of different statistics from a text file for a homework assignment. I have found everything except the shortest line that is not a blank line. Can someone help me solve this problem?


def stats():
  linecount = 0
  blankline = 0
  largeline = ''
  largelinelen = 0
  linelength = 0
  nonemptyline = 0
  shortline = ''
  shortlinelen = largelinelen
  inFileName = input("Please enter the name of the file to copy: ")
  inFile = open(inFileName)
  for line in inFile:
     linecount = linecount + 1
     linelength = linelength + len(line)
     if line.startswith('\n'):
        blankline = blankline + 1 
     if len(line) > largelinelen:
                largelinelen = len(line)
                largeline = line
     if len(line) < shortlinelen and len(line) > ('\n'):
                  shortlinelen = len(line)
                  shortline = line 
  print("toal lines:", linecount)
  print("blank lines:", blankline)
  print("largest line is:", largeline) 
  print("largest line length is:", len(largeline))
  print("total length of lines:", linelength)
  print("average line length is:", "%1.3f" % (linelength/linecount))
  print("average blank lines is:", "%1.3f" % (linecount/blankline))
  print('average number of non empty lines are:', "%1.3f" % ((linecount - blankline) / linecount))
  print("average non empty")
  print("shortest line is:", shortline) 
  print("shortest line length is:", len(shortline))
5 Years
Discussion Span
Last Post by woooee

It would be an else statement after the blankline code

if line.startswith('\n'):
        blankline = blankline + 1 
        if len(line.strip()) < shortest:
            shortest = len(line.strip())

# or better yet
     line = line.strip()
     if len(line) == 0:
        blankline = blankline + 1 
        if len(line) < shortest:
            shortest = len(line)
# and 
        if len(line) > largelinelen:  ## same indent level

Edited by woooee: n/a


hmm i see what you are trying to do. But what is "shortest" initially set at?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.