2 Replies - 2323 Views - Last Post: 18 October 2011 - 06:54 AM

#1 atik97   User is offline

  • ???
  • member icon

Reputation: 144
  • View blog
  • Posts: 715
  • Joined: 16-September 08

How many words in a file?

Posted 19 January 2009 - 04:11 PM

Description: You need to import string moduleFind out the number of words in a given file.
from string import *
def countWords(s):
    words=split(s)
    return len(words)       #returns the number of words

filename=open("welcome.txt",'r')    #open an file in reading mode

total_words=0

for line in filename:
    total_words=total_words + countWords(line)      #counts the total words

print total_words

Is This A Good Question/Topic? 0
  • +

Replies To: How many words in a file?

#2 ATC3   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 54
  • Joined: 04-October 11

Re: How many words in a file?

Posted 04 October 2011 - 05:43 AM

What about adding an argv to be able to pick your own file at the time of running the script. Then you would not have to reprogram it.
Was This Post Helpful? 0
  • +
  • -

#3 MirrorFish   User is offline

  • New D.I.C Head
  • member icon

Reputation: 7
  • View blog
  • Posts: 27
  • Joined: 29-March 11

Re: How many words in a file?

Posted 18 October 2011 - 06:54 AM

Hello, May I suggest to count only a number of spaces between words ? This way no split() is needed - just walk through all characters in the file and calculate spaces. Don't forget to decrease the resulting sum by one to reflect the fact that there is no space leading the first word. Regards
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1