我需要用空格替换所有非ASCII (\x00-\x7F)字符。我很惊讶这在Python中并不是那么简单,除非我遗漏了什么。下面的函数只是删除所有非ASCII字符:
def remove_non_ascii_1(text):
return ''.join(i for i in text if ord(i)<128)
根据字符码位中的字节数,用空格量替换非ASCII码字符(即用3个空格替换–
字符):
def remove_non_ascii_2(text):
return re.sub(r'[^\x00-\x7F]',' ', text)
如何用一个空格替换所有非ASCII码字符?
Of the myriad of similar SO questions,none address C14<代码>C15<代码>C16<代码>C17<代码>C18<代码>C19,<代码>C20另外寻址所有非ascii字符,而不是特定字符。
发布于 2013-11-20 02:11:36
您的''.join()
表达式正在过滤,删除任何非ASCII码;您可以改用条件表达式:
return ''.join([i if ord(i) < 128 else ' ' for i in text])
这将逐个处理字符,并且每个替换的字符仍将使用一个空格。
您的正则表达式应该只用空格替换连续的非ASCII字符:
re.sub(r'[^\x00-\x7F]+',' ', text)
请注意那里的+
。
发布于 2016-02-19 04:50:55
为了获得与原始字符串最相似的表示,我推荐使用the unidecode module
# python 2.x:
from unidecode import unidecode
def remove_non_ascii(text):
return unidecode(unicode(text, encoding = "utf-8"))
然后,您可以在字符串中使用它:
remove_non_ascii("Ceñía")
Cenia
发布于 2013-11-20 02:29:15
对于字符处理,请使用Unicode字符串:
PythonWin 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32.
>>> s='ABC马克def'
>>> import re
>>> re.sub(r'[^\x00-\x7f]',r' ',s) # Each char is a Unicode codepoint.
'ABC def'
>>> b = s.encode('utf8')
>>> re.sub(rb'[^\x00-\x7f]',rb' ',b) # Each char is a 3-byte UTF-8 sequence.
b'ABC def'
但请注意,如果字符串包含分解的Unicode字符(例如,分隔字符和组合重音标记),您仍然会遇到问题:
>>> s = 'mañana'
>>> len(s)
6
>>> import unicodedata as ud
>>> n=ud.normalize('NFD',s)
>>> n
'mañana'
>>> len(n)
7
>>> re.sub(r'[^\x00-\x7f]',r' ',s) # single codepoint
'ma ana'
>>> re.sub(r'[^\x00-\x7f]',r' ',n) # only combining mark replaced
'man ana'
https://stackoverflow.com/questions/20078816
复制相似问题