One way is to use re.sub, that's my preferred way.
import re
my_str = "hey th~!ere"
my_new_string = re.sub('[^a-zA-Z0-9 \n\.]', '', my_str)
print my_new_string
Output:
hey there
Another way is to use re.escape:
import string
import re
my_str = "hey th~!ere"
chars = re.escape(string.punctuation)
print re.sub('['+chars+']', '',my_str)
Output:
hey there
Just a small tip about parameters style in python by PEP-8 parameters should be remove_special_chars and not removeSpecialChars
Also if you want to keep the spaces just change [^a-zA-Z0-9 \n\.] to [^a-zA-Z0-9\n\.]
One way is to use re.sub, that's my preferred way.
import re
my_str = "hey th~!ere"
my_new_string = re.sub('[^a-zA-Z0-9 \n\.]', '', my_str)
print my_new_string
Output:
hey there
Another way is to use re.escape:
import string
import re
my_str = "hey th~!ere"
chars = re.escape(string.punctuation)
print re.sub('['+chars+']', '',my_str)
Output:
hey there
Just a small tip about parameters style in python by PEP-8 parameters should be remove_special_chars and not removeSpecialChars
Also if you want to keep the spaces just change [^a-zA-Z0-9 \n\.] to [^a-zA-Z0-9\n\.]
str.replace is the wrong function for what you want to do (apart from it being used incorrectly). You want to replace any character of a set with a space, not the whole set with a single space (the latter is what replace does). You can use translate like this:
removeSpecialChars = z.translate ({ord(c): " " for c in "!@#$%^&*()[]{};:,./<>?\|`~-=_+"})
This creates a mapping which maps every character in your list of special characters to a space, then calls translate() on the string, replacing every single character in the set of special characters with a space.
I have the following code.
The aim is to remove all special characters from the column of a DataFrame, although it does not matter if all special characters are removed from the DataFrame.
The code i have used is:
words = combined_body_title.title_body.str.split().explode().str.replace("[?.',)(/:!]","", regex=True)
This works until i put in quotation markets or brackets.
I have read the documentation, from that i think i am using it wrong. I should not be trying to change more than one character within the str.replace, but for some reason it still works just not for brackets and quotation marks.
If you could suggest an alternative solution or help me fix this one i would really appreciate it!
replace - replacing special characters in string Python - Stack Overflow
Special characters in Python string replace - Stack Overflow
Python String replacing special characters - Stack Overflow
How to replace all those Special Characters with white spaces in python? - Stack Overflow
import re
s=re.sub("[_list of special characters_]","",_your string goes here_)
print(s)
An example for this..
str="Hello$@& Python3$"
import re
s=re.sub("[$@&]","",str)
print (s)
#Output:Hello Python3
Explanation goes here..
s=re.sub("[$@&]","",s)
- Pattern to be replaced → “[$@&]”
- [] used to indicate a set of characters
- [$@&] → will match either $ or @ or &
- The replacement string is given as an empty string
- If these characters are found in the string, they’ll be replaced with an empty string
you can use Series.replace with a dictionary
#d = { 'actual character ':'replacement ',...}
df.columns = df.columns.to_series().replace(d, regex=True)
Assuming you mean to change everything non-alphanumeric, you can do this on the command line:
cat foo.txt | sed "s/[^A-Za-z0-99]/ /g" > bar.txt
Or in Python with the re module:
import re
original_string = open('foo.txt').read()
new_string = re.sub('[^a-zA-Z0-9\n\.]', ' ', original_string)
open('bar.txt', 'w').write(new_string)
import string
specials = '-"/.' #etc
trans = string.maketrans(specials, ' '*len(specials))
#for line in file
cleanline = line.translate(trans)
e.g.
>>> line = "Indo-American pvt/ltd"
>>> line.translate(trans)
'Indo American pvt ltd'
If, s=url['title'] makes s equal to this:
In [48]: s=u'Oscar Winners Best Pictures Box Set \xc2\xa36.49'
Then the problem is
- in the code that defines
url, - or else the content from the web is mal-formed.
If Case 1, we'd need to see the code that defines url.
If Case 2, a quick-and-dirty workaround would be to encode the unicode object s with the raw-unicode-escape codec:
In [49]: print(s)
Oscar Winners Best Pictures Box Set £6.49
In [50]: print(s.encode('raw-unicode-escape'))
Oscar Winners Best Pictures Box Set £6.49
See also this SO question.
Regarding titles like s=u'Star Trek XI £3.99': Again, it would be nice fix the problem before it gets to this stage -- perhaps by looking at how url is defined. But assuming the content from the web is mal-formed, a workaround would be:
In [86]: import re
In [87]: print(re.sub(r'&#x([a-fA-F\d]+);',lambda m: unichr(int(m.group(1),base=16)),s))
Star Trek XI £3.99
A little bit of explanation:
Note that
In [51]: x=u'£'
In [53]: x.encode('utf-8')
Out[53]: '\xc2\xa3'
So the unicode object u'£', encoded with the utf-8 codec, becomes the string object '\xc2\xa3'.
Somehow, url['title'] is getting defined to be the unicode object
u'\xc2\xa3'. (The u makes a big difference!)
Thus we have u'\xc2\xa3' when we desire '\xc2\xa3'.
Encoding the unicode object u'\xc2\xa3' with the raw-unicode-escape codec transforms it to '\xc2\xa3'.
Edit: you have your objects already in unicode. Seems to me there is no reason to actually use enocde/decode at all.
>>> print u'Oscar Winners Best Pictures Box Set \xc2\xa36.49'.replace(u'Â','')
Oscar Winners Best Pictures Box Set £6.49
However it seems to me that something is wrong there. The unicode objects are actually not unicode; see:
>>> print 'Oscar Winners Best Pictures Box Set \xc2\xa36.49'.decode('utf8')
Oscar Winners Best Pictures Box Set £6.49
The repr() you posted should not be unicode object. That's why I was asking where are you getting the data, there is something wrong.
Thanks to The fourth bird and hojkas !
I understood what was going wrong and i finally ended up with this working code (for any special characters but keep spaces) :
titre = '4K UL*tra & H~~~~D | SAMS!!!!UNG U,HD De;mo׃ LE$D T^^V'
print('original : '+ titre)
for i in titre:
if not i.isalnum() and not i.isspace():
titre=titre.replace(i,'')
print('modified : '+ titre)
#Output :
#original : 4K UL*tra & H~~~~D | SAMS!!!!UNG U,HD De;mo׃ LE$D T^^V
#modified : 4K ULtra HD SAMSUNG UHD Demo LED TV
You could achieve this by using the sub() functionality of the re package.
The issue you're seeing is due to the fact that what appears to be an ASCII colon is, in fact, a HEBREW PUNCTUATION SOF PASUQ with a Unicode value of 05C3
Therefore:
import re
titre = "4K ULtra HD | SAMSUNG UHD Demo׃ LED TV"
PATTERN = r"[\?:\*~\|#/\"\u05c3]"
print(re.sub(PATTERN, "-", titre))
Output:
4K ULtra HD - SAMSUNG UHD Demo- LED TV