Your ''.join() expression is filtering, removing anything non-ASCII; you could use a conditional expression instead:
return ''.join([i if ord(i) < 128 else ' ' for i in text])
This handles characters one by one and would still use one space per character replaced.
Your regular expression should just replace consecutive non-ASCII characters with a space:
re.sub(r'[^\x00-\x7F]+',' ', text)
Note the + there.
Your ''.join() expression is filtering, removing anything non-ASCII; you could use a conditional expression instead:
return ''.join([i if ord(i) < 128 else ' ' for i in text])
This handles characters one by one and would still use one space per character replaced.
Your regular expression should just replace consecutive non-ASCII characters with a space:
re.sub(r'[^\x00-\x7F]+',' ', text)
Note the + there.
For you the get the most alike representation of your original string I recommend the unidecode module:
Python 2
from unidecode import unidecode
def remove_non_ascii(text):
return unidecode(unicode(text, encoding = "utf-8"))
Then you can use it in a string:
remove_non_ascii("Ceñía")
Cenia
Python 3
from unidecode import unidecode
unidecode("Ceñía")
regex - Python - Replace non-ascii character in string (») - Stack Overflow
python - Replace special characters with ASCII equivalent - Stack Overflow
Replace non-ASCII character in Python: eg, ' vs. ’ - Stack Overflow
replace non ascii characters in python - Stack Overflow
My script uses strings that sometimes include foreign characters that don't exist in ASCII. (ö, ê, etc.) How do I get them to work in Python? For example, the character 'µ' gets changed to 'xb5', which makes my script fail. Is there any way to make this work?
I read somewhere that Python 3 changes the way it handles encodings, should I try to upgrade instead?
In order to replace the content of string using str.replace() method; you need to firstly decode the string, then replace the text and encode it back to the original text:
>>> a = "hi »"
>>> a.decode('utf-8').replace("»".decode('utf-8'), "").encode('utf-8')
'hi '
You may also use the following regex to remove all the non-ascii characters from the string:
>>> import re
>>> re.sub(r'[^\x00-\x7f]',r'', 'hi »')
'hi '
@Moinuddin Quadri's answer fits your use-case better, but in general, an easy way to remove non-ASCII characters from a given string is by doing the following:
# the characters '¡' and '¢' are non-ASCII
string = "hello, my name is ¢arl... ¡Hola!"
all_ascii = ''.join(char for char in string if ord(char) < 128)
This results in:
>>> print(all_ascii)
"hello, my name is arl... Hola!"
You could also do this:
''.join(filter(lambda c: ord(c) < 128, string))
But that's about 30% slower than the char for char ... approach.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unicodedata
text = u'Cześć'
print unicodedata.normalize('NFD', text).encode('ascii', 'ignore')
The package unidecode worked best for me:
from unidecode import unidecode
text = "Björn, Łukasz and Σωκράτης."
print(unidecode(text))
# ==> Bjorn, Lukasz and Sokrates.
You might need to install the package:
pip install unidecode
The above solution is easier and more robust than encoding (and decoding) the output of unicodedata.normalize(), as suggested by other answers.
# This doesn't work as expected:
ret = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore')
print(ret)
# ==> b'Bjorn, ukasz and .'
# Besides not supporting all characters, the returned value is a
# bytes object in python3. To yield a str type:
ret = ret.decode("utf8") # (not required in python2)
You need to decode the string
# -*- coding: utf-8 -*-
clean = "you’ll".decode('utf-8')
clean = clean.replace('’'.decode('utf-8'),' ')
print clean
This prints
you ll
which is as expected
It's probably not the best answer, but a simple solution is to just handle the exception:
clean2 = ""
for ch in clean:
try:
clean2 += " " if ch == "'" else clean2 += ch
except UnicodeDecodeError:
clean2 += 'vs.'
If all you want to do is degrade accented characters to their non-accented equivalent:
>>> import unicodedata
>>> unicodedata.normalize('NFKD', u"m\u00fasica").encode('ascii', 'ignore')
'musica'
Now, just to supplement that answer: It may be the case that your data does not come in unicode (i.e. you are reading a file with another encoding and you cannot prefix the string with a "u"). Here's a snippet that may work too (mostly for those reading files in English).
import unicodedata
unicodedata.normalize('NFKD',unicode(someString,"ISO-8859-1")).encode("ascii","ignore")
You've got an encoding problem. Instead of trying to remove this characters, look for the encoding of the page, then when you read the file, use the codecs module instead of open(), using the proper character encoding.
filtered_content = filter(lambda x: x in string.printable, content)
This solved my problem. Thank you!