samedi 21 février 2015

Python 3:How do I count the words in the string without using anything more complicated than line.strip()

So this is the function I have so far, it's supposed to read a text file and return the total number of words. You cannot use anything more complicated than line.strip() (str.split, srt.partition). For some strange reason it's counting some extra character from text file, including \n's. Here's one of the text files:



Words make up other words.
This is a line.
Sequences of words make sentences.
I like words but I don't like MS Word.
There's another word for how I feel about MSWord: @#%&


In this text file it has a total of 33 words but my program is counting 34. It's not showing up properly here but the first two sentences have it's own line, the third has it's own line and two spaces in the very beginning then the sentence, the fouth had it's own line, and last sentence has it's own line but begins with 8 spaces, then sentence. Thanks!



def countWords(textFileName):
words = 0
for char in textFileName:
if char == " " or char == ".":
words = words + 1
if char != " " and char != ".":
pass
return words


def main():
textFileName = input("Enter textFileName: ")
total = 0
for char in open(textFileName):
total = total + countWords(char)
print(total, "words")
main()

Aucun commentaire:

Enregistrer un commentaire