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

Change line 8 to

for line in fin.readlines():
commented: Thanks for the help +0

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?

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

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)

Read about conditional statements here.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.