Even if you iterate over the lines of a file (strange use of sys.stdin), your code does not make much sense. It might give you the number of lines, but surely not the number of words or characters this way.
Lardmeister
Posting Virtuoso
1,749 posts since Mar 2007
Reputation Points: 407
Solved Threads: 44
I am not sure where you get that stdin notion from? Python has its own functions for input and file handling:
# write a test text file
jingle = """Dashing through the snow
In a one horse open sleigh
Over the fields we go
Laughing all the way
Bells on bob tail ring
Making spirits bright
What fun it is to ride and sing
A sleighing song tonight
"""
write_text = open("JingleBell.txt", "w")
write_text.write(jingle)
write_text.close()
# use the text file you have just created or
# pick a filename you have in your working directory
filename = "JingleBell.txt"
# bring the whole text in as a string
read_text = open(filename, "r")
text = read_text.read()
read_text.close()
# assume each line ends with a '\n'
num_lines = text.count('\n')
# assume each word is separated by whitespaces
num_words = len(text.split(None))
# assume all characters including newline
num_char = len(text)
# show results
print "Number of lines", num_lines
print "Number of words", num_words
print "Number of characters", num_char
Lardmeister
Posting Virtuoso
1,749 posts since Mar 2007
Reputation Points: 407
Solved Threads: 44
Thanks G-Do, we were told by our instructor to always use split(None) rather than just split(). I imagine it is just style.
Lardmeister
Posting Virtuoso
1,749 posts since Mar 2007
Reputation Points: 407
Solved Threads: 44