[Tutor] can this be done easerly
Evert Rol
evert.rol at gmail.com
Mon Aug 30 12:04:08 CEST 2010
> For a exerise I made this one :"
>
> import string
> def extract_words(s):
> """
> >>> extract_words('Now is the time! "Now", is the time? Yes, now.')
> ['now', 'is', 'the', 'time', 'now', 'is', 'the', 'time', 'yes', 'now']
> >>> extract_words('she tried to curtsey as she spoke--fancy')
> ['she', 'tried', 'to', 'curtsey', 'as', 'she', 'spoke', 'fancy']
> """
> word= ""
> s=string.lower(s)
> for char in s :
> if ord(char) >=65 and ord(char) <= 122 or ord(char)==32 or ord(char)==45:
> word= word + char
> word=string.split(word, "--")
> word=string.join(word, " ")
> word=word.replace (" ", " ")
> word=string.split(word, " ")
> return word
>
> if __name__ == '__main__':
> import doctest
> doctest.testmod()
>
> But now I wonder if this can be done more easerly ?
Using regular expressions could work, depending on your view of regular expressions being 'easy':
import re
re.split('\W+', s.lower())
will do most of what you want (though you'll end up with the occasional empty string.
Evert
More information about the Tutor
mailing list