[Tutor] anagrams

Gonçalo Rodrigues op73418 at mail.telepac.pt
Wed Nov 5 17:47:35 EST 2003


On Wed, 5 Nov 2003 14:34:17 -0800 (PST), you wrote:

[text snipped]

>
>For some reason, when I iterated over a file, it gave
>me lines, not words. Is this what it is supposed to
>do, or could there be something wrong with how I have
>Python configured?
>

It's correct, the iterator over a file gives lines not words. But it's
very simple to have an iterator over words. Untested:

def iterword(f):
    """Iterate over the words of a file.

    Args: a file object.
    """
    for line in f:
        #Split the line in words.
        words = line.split()
        for word in words:
            yield word

In splitting the line in words I have used the simplest possible
device: the string method split that splits a string on whitespace.
More sophisticated (and correct) ways of splitting a line in words can
be achieved with the re module, for example.

With my best regards,
G. Rodrigues



More information about the Tutor mailing list