Building counts lines , words and chars – Python

Program counts lines, words and chars
Here are two options

First option

Used: for , if

counts.png
To copy or see all commands you can click on Details button below

 

#!/usr/bin/python
”’
author: Hopeless
task: Write a program that counts lines, words and chars in a given file
”’
file = raw_input(‘please enter file name and locate if need:’)fileo = open(file,’r+’)
chars=0
words=0
lines=0

# calculate number of words
fileo = open(file,’r+’)
for word in fileo.read().split():
if word != ‘ ‘:
if word != ‘\n’:
words+=1
#print word
fileo.close()

# calculate number of chars
fileo = open(file,’r+’)
for word in fileo.read():
if word != ‘ ‘:
if word != ‘\n’:
chars+=1
fileo.close()

# calculate number of lines
fileo = open(file,’r+’)
for word in fileo.read().split(“\n”):
#print word
lines+=1
fileo.close()

print ‘number of words in file :’, words
print ‘number of chars in file :’, chars
print ‘number of lines in file :’, lines

 

First we have to download a file that you can work on it.
Then we run the Python file
And put the name of the file for inspection when requested to do so

Untitled.png

second option

Used: import sys , if , try , except , else

counts-g.png
To copy or see all commands you can click on Details button below

 

#!/usr/bin/python
”’
author: Hopeless
task: Write a program that counts lines, words and chars in a given file
”’
import sys# file = raw_input(‘please enter file name and locate if need:’)

if len(sys.argv) > 1:
try:
filex = open(sys.argv[1],’r’)
text = filex.read()
filex.close()

#print # of lines
print ‘Lines:’, text.count(‘\n’)+1

#print #of words
wordcount = text.split(None)
print ‘Words:’, len(wordcount)

#print # of chars
print ‘Chars:’, len(text)

except Exception, e:
print ‘I can\’t find the file, maybe try full path?…’
exit(0)

else:
print ‘Hi this prog it like linux wc…’
print ‘Usage: checkfilesgil.py [filename]\n’
print ‘Example: checkfilesgil.py sheker.txt’

 

First we have to download a file that you can work on it.
Then we run the Python file And that line we will put the filename

Untitled1.png

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s