def main():
    splash()
    wordTotal = 0
    longestWord = 0

    fin = open("constitu.txt")

    for line in fin:
         #n = fin.readline()
        wordLine = line.split()
         #word = wordLine.split()
        wordTotal += len(wordLine)
         #if len(word) >= 15:
             #longestWord += 1
             #print word

    print "This constitution has ",wordTotal, " words."
    
def splash():
    print "This program is going to read the Constitution " \
           + "of the United States of America " \
           + "and determine the length and longest word in it.\n"

main()

I'm trying to read the constitution from a file I have in the same folder as this program. the file name is constitu.txt

whenever i add in line "n = fin.readline()", i get an Mixed Iteration variable error:
File "C:\COP1000\HW07-CLD (Unfinished).py", line 13, in main
text = fin.readline()
ValueError: Mixing iteration and read methods would lose data

when i take that line out, i get no errors but my program will not count the words in my .txt file.

Any help would be appreciated, i'm using python v2.7

I have Python 2.6 and it worked fine for me without my uncommenting #n = fin.readline() or anything else. I made no changes except the file path and it showed me a word count for the my file (not the constitution but some other file in my folder).

When it doesn't work for you, does the wordTotal variable equal zero, or in what way does it not work?

Edited 6 Years Ago by d5e5: n/a

whenever i add in line "n = fin.readline()", i get an Mixed Iteration variable error:

for line in fin:
and
n = fin.readline()
do the same thing. Choose one or the other. You can also do a
for line in open("constitu.txt"):
(is the same thing) as well. Also, a hint below. And note that punctuation will be included in the word length if you don't remove it.

def main():
    splash()
    wordTotal = 0
    longestWord = 0
 
    fin = open("constitu.txt")
 
    for line in fin:
         #n = fin.readline()
        wordLine = line.split()
        ##------------------------------------
        for word in wordLine:
            print len(word), word, len(word) > longestWord
        ##------------------------------------
        #word = wordLine.split()
        wordTotal += len(wordLine)
         #if len(word) >= 15:
             #longestWord += 1
             #print word

Edited 6 Years Ago by woooee: n/a

How about how to keep track of the longest word in constitu.txt?
i tried this:

for word in wordLine:
            len(word)> longestWord
            longestWord += 1

but all it does is the same as this:

for line in fin:
        wordLine = line.split()
        wordTotal += len(wordLine)
This question has already been answered. Start a new discussion instead.