Python Forum
New in Python. Have question on my code.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
New in Python. Have question on my code.
#1
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)
Reply
#2
What is the average of 3, 4, 5? How did you do that?
Reply
#3
  • 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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Question re: running code in Editor (i.e. Atom) vs Python interpreter rok 3 2,419 Jun-29-2020, 09:20 PM
Last Post: bowlofred
  Newb question: Debugging + Linting Python in Visual Studio Code Drone4four 1 2,423 Apr-15-2019, 06:19 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020