I am learning python on my own
how to count words in a text file?
3 Replies - 147 Views - Last Post: 14 January 2013 - 09:20 AM
#1
how to counting words in a text file using python
Posted 14 January 2013 - 07:35 AM
Replies To: how to counting words in a text file using python
#2
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.
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")
#3
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
#4
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.
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote





|