Hi everybody,

Pls give me sb. a hint. I do this following exercise but I struggle with reading another lines of txt. Here is the text:

Exercise 9.1 Write a program that reads words.txt and prints only the words with more than 20
characters (not counting whitespace).

here is my version for the first line but I struggle to get through the all lines fullfiling the condition (20 char without whitespace)

def test():
    fin = open('words.txt')
    count = 0
    word = fin.readline()
    x = len(word)
    for i in word:
        if i == ' ':
            count = count + 1
    y = x - count
    if y >= 20:
        print word
        return word
    else:
        print 'words have only', y, 'char'

test()

pls can anybody help?

many thanks

vlad

Edited 6 Years Ago by vegaseat: added code tags

Use code tag now we can not see if your indentation is correct.

You dont have strip() in your script.

>>> a = 'test      \n'
>>> len(a)
11
>>> #Without whitespace and new line
>>> b = a.strip()
>>> b
'test'
>>> len(b)
4
>>>

So you read in file(for loop) strip() it and use len() to find word that has more than 20 characters.

fin = open('c:/python26/words.txt')

for line in fin:
    word = line.strip()
    if len(word) > 20:
        print word
'''--> Output
counterdemonstrations
hyperaggressivenesses
microminiaturizations
'''

Edited 6 Years Ago by snippsat: n/a

Use code tag now we can not see if your indentation is correct.

You dont have strip() in your script.

>>> a = 'test      \n'
>>> len(a)
11
>>> #Without whitespace and new line
>>> b = a.strip()
>>> b
'test'
>>> len(b)
4
>>>

So you read in file(for loop) strip() it and use len() to find word that has more than 20 characters.

fin = open('c:/python26/words.txt')

for line in fin:
    word = line.strip()
    if len(word) > 20:
        print word
'''--> Output
counterdemonstrations
hyperaggressivenesses
microminiaturizations
'''

thank you very much, i am going to try your hint.

vlad

thank you very much, i am going to try your hint.

vlad

I've tried it and it works! I can not believe it was so simple!!! I struggle how to solve it!

again thank you very much!!!

vlad

This question has already been answered. Start a new discussion instead.