How to replace all those special characters with white spaces in python ?
I have a list of names of a company . . .
Ex:-[myfiles.txt]
MY company.INC
Old Wine pvt
master-minds ltd
"apex-labs ltd"
"India-New corp"
Indo-American pvt/ltd
Here, as per the above example . . . I need all the special characters[-,",/,.] in the file myfiles.txt
must be replaced with a single white space and saved into another text file myfiles1.txt
.
Can anyone please help me out?
e.g.
Assuming you mean to change everything non-alphanumeric, you can do this on the command line:
Or in Python with the
re
module:At first i thought to provide a string.maketrans/translate example, but maybe you are using some utf-8 encoded strings and the ord() sorted translate-table will blow in your face, so i thought about another solution:
It's not the fastest way, but easy to grasp and modify.
So if your text is non-ascii you could decode
conversion
and the text-strings to unicode and afterwards reencode in whichever encoding you want to.While maketrans is the fastes way to do it, I never remerber the syntax. Since speed is rarely an issue and I know regular expression, I would tend to do this:
This has the additional benefit of declaring the character you accept instead of the one you reject, which feels easier in this case.
Of couse if you are using non ASCII caracters you'll have to go back to removing the characters you reject. If there are just punctuations sign, you can do:
But you'll notice