Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

correctly strip : char with Regex

Tags:

python

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 am getting:

['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 strings that happen to contain : ? I thought using \b would be enough...

like image 734
edgarmtze Avatar asked Apr 02 '26 03:04

edgarmtze


2 Answers

I think you intended to pass a raw string to re.sub (notice the r).

result = re.sub(r"\b[^\w\d_]+\b", " ",  s ).split()

Returns:

['The', 'saddest', 'aspect', 'of', 'life', 'right', 'now', 'is', 'science', 'gathers', 'knowledge', 'faster', 'than', 'society', 'gathers', 'wisdom.']
like image 127
Alexander O'Mara Avatar answered Apr 03 '26 18:04

Alexander O'Mara


You forgot to make it a raw 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.']
like image 40
jamylak Avatar answered Apr 03 '26 18:04

jamylak