Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Regex - Remove special characters but preserve apostraphes

Tags:

python

regex

I am attempting to remove all special characters from some text, here is my regex:

pattern = re.compile('[\W_]+', re.UNICODE)
words = str(pattern.sub(' ', words))

Super simple, but unfortunately it is causing problems when using apostrophes (single quotes). For example, if I had the word "doesn't", this code is returning "doesn".

Is there any way of adapting this regex so that it doesn't remove apostrophes in instances like this?

edit: here is what I am after:

doesn't this mean it -technically- works?

should be:

doesn't this mean it technically works

like image 742
Hanpan Avatar asked Jul 09 '12 21:07

Hanpan


2 Answers

Like this?

>>> pattern=re.compile("[^\w']")
>>> pattern.sub(' ', "doesn't it rain today?")
"doesn't it rain today "

If underscores also should be filtered away:

>>> re.compile("[^\w']|_").sub(" ","doesn't this _technically_ means it works? naïve I am ...")
"doesn't this  technically  means it works  naïve I am    "
like image 169
tobixen Avatar answered Oct 19 '22 12:10

tobixen


I was able to parse your sample into a list of words using this regex: [a-z]*'?[a-z]+.

Then you can just join the elements of the list back with a space.

like image 24
Mike Z Avatar answered Oct 19 '22 11:10

Mike Z