1.11M Members

Finding shortest non blank line in text file

 
0
 

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?

Thanks

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))
  inFile.close()
 
0
 

It would be an else statement after the blankline code

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

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

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

 
0
 

Generally you set it to the length of the first record that is not blank/empty.

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: