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

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
'''

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

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.