Correct strip: char with regex
I want to get words in a text string in python
s = "The saddest aspect of life right now is: science gathers knowledge faster than society gathers wisdom."
result = re.sub("\b[^\w\d_]+\b", " ", s ).split()
print result
I get:
['The', 'saddest', 'aspect', 'of', 'life', 'right', 'now', 'is:', 'science', 'gathers', 'knowledge', 'faster', 'than', 'society', 'gathers', 'wisdom.']
How can I get "is" and not "is:" on lines that contain :
? I thought it \b
would be enough to use ...
source to share
You forgot to make it a string literal ( r".."
)
>>> import re
>>> s = "The saddest aspect of life right now is: science gathers knowledge faster than society gathers wisdom."
>>> re.sub("\b[^\w\d_]+\b", " ", s ).split()
['The', 'saddest', 'aspect', 'of', 'life', 'right', 'now', 'is:', 'science', 'gathers', 'knowledge', 'faster', 'than', 'society', 'gathers', 'wisdom.']
>>> re.sub(r"\b[^\w\d_]+\b", " ", s ).split()
['The', 'saddest', 'aspect', 'of', 'life', 'right', 'now', 'is', 'science', 'gathers', 'knowledge', 'faster', 'than', 'society', 'gathers', 'wisdom.']
source to share
As other answers pointed out, you need to define a string literal using r
like this:(r"...")
If you want to split periods, I believe you can simplify the regex:
result = re.sub(r"[^\w' ]", " ", s ).split()
As you probably know, the metacharacter \w
separates the string of everything that is not az, AZ, 0-9
So, if you can expect your proposals will not contain numbers that should do the trick.
source to share