jeudi 5 novembre 2015

How to count all lines, words, and characters in a file

I'm trying to write a program that counts all of the lines, words, and characters in a .txt file. I have the lines coming out but I don't know how to do the words or characters.

"""Write a function stats() that takes one input argument: the name of a text file. The function should print, on the screen, the number of lines, words, and characters in the file; your function should open the file only once.

stats( 'example.txt') line count: 3 word count: 20 character count: 98"""

def stats(inF):

inFile=open(inF,'r')  
text=inFile.readlines() 
textLen=len(text)  
print(textLen) 

 wordCount=0
 charCount=0

 for word in inFile.read().split():
    if word in inFile:
         wordCount = +1
      else:
          wordCount = 1
   print(wordCount)

print(stats("n.txt"))

Aucun commentaire:

Enregistrer un commentaire