Python Forum

Full Version: New in Python. Have question on my code.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The problem is i have to print out the average length of words in each lines in a txt documents.

My code so far: i know how to count the number in each line and how many words in each line, but have no idea how to start a average length of words.

count=0
with open('win95coolest.txt') as book:
    for lines in book:
        count+=1
        print(count,(len(lines.split())), lines)
What is the average of 3, 4, 5? How did you do that?
  • create another variable at start to keep count of total number of words total_words = 0
  • strip line feeds from lines before split,
    lines = lines.strip()
  • split lines into slines
    Use a new name saving original for printing
  • calculate line length of split line
  • add line length to total_words
  • print line number, length and lines
  • Continue loop
  • after loop (not part of loop) calculate and print average line length