views:

49

answers:

2

I am writing a piece of code which will extract words from running text. This text can contain delimiters like \r,\n etc. which might be there in text.

I want to discard all these delimiters and only extract full words. How can I do this with Python? any library available for crunching text in python?

+4  A: 

Assuming your definition of "word" agrees with that of the regular expression module (re), that is, letters, digits and underscores, it's easy:

import re
fullwords = re.findall(r'\w+', thetext)

where thetext is the string in question (e.g., coming from an f.read() of a file object f open for reading, if that's where you get your text from).

If you define words differently (e.g. you want to include apostrophes so for example "it's" will be considered "one word"), it isn't much harder -- just use as the first argument of findall the appropriate pattern, e.g. r"[\w']+" for the apostrophe case.

If you need to be very, very sophisticated (e.g., deal with languages that use no breaks between words), then the problem suddenly becomes much harder and you'll need some third-party package like nltk.

Alex Martelli
Thanks! This really helped me solve the issue. I had a look at nltk but unfortunately due to the C library installation dependency, I cannot use it with Google App Engine.
demos
+1  A: 

Assuming your delimiters are whitespace characters (like space, \r and \n), then basic str.split() does what you want:

>>> "asdf\nfoo\r\nbar too\tbaz".split()
['asdf', 'foo', 'bar', 'too', 'baz']
Stephen
If it's OK to consider _every_ punctuation character to be part of the "word" it touches, yes, but that's not a very frequent use case in real-world application (e.g., parsing this comment you wouldn't want to see `"touches,"` complete with trailing comma as "a word";-).
Alex Martelli
@Alex Martelli : Yeah, good point about punctuation, but from the question it wasn't clear whether that was necessary - the examples of delimeters were all whitespace. OTOH, it might be important to keep certain punctuation with the word (e.g. '$', '-', '%'...). I'd disagree that this isn't a common use case though, it really depends on what you're building - splitting tabular output is one thing, parsing natural language is another :)
Stephen