3 Replies - 874 Views - Last Post: 14 January 2013 - 09:20 AM Rate Topic: -----

#1 swazipython  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 14-January 13

how to counting words in a text file using python

Posted 14 January 2013 - 07:35 AM

I am learning python on my own
how to count words in a text file?
Is This A Good Question/Topic? 0
  • +

Replies To: how to counting words in a text file using python

#2 darek9576  Icon User is offline

  • D.I.C Lover

Reputation: 198
  • View blog
  • Posts: 1,691
  • Joined: 13-March 10

Re: how to counting words in a text file using python

Posted 14 January 2013 - 07:53 AM

Python is a great language to learn. The best thing you can do is to grab a book or just browse the internet for resources. There are good articles on the internet on Python.

To answer your question: you need to know how to open a file in python, grab the contents and iterate over them. Usually when you deal with files in any language, you should learn about catching exceptions.

I am sure there is a cleaner way of achieving the task.
import itertools

def openFile(fileName):
    lst = []
    try:
        fin = open(fileName)
        for line in fin:
            lst.append(line.strip().split())
    
        print("The lenght of the file is: ", len(list(itertools.chain.from_iterable(lst))))
        fin.close()        
    except:
        print("Could not open the file")
        


Was This Post Helpful? 0
  • +
  • -

#3 swazipython  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 14-January 13

Re: how to counting words in a text file using python

Posted 14 January 2013 - 08:14 AM

thank you for your response,please if you dont mind,take me through the step.like explain what everything means..i am only two weeks into programming,have no books so am relying on help from kind friends like you
Was This Post Helpful? 0
  • +
  • -

#4 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7807
  • View blog
  • Posts: 13,203
  • Joined: 19-March 11

Re: how to counting words in a text file using python

Posted 14 January 2013 - 09:20 AM

Try working your way through the tutorials at python.org. They're free, and they'll get you started pretty well. Of course you should feel free to ask about anything you find confusing there, but you might as well start with the existing documentation.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1