Nat*_*ate 35
总是有正则表达式; 只列出方括号内的所有违规字符,如下所示:
import re
print re.sub(r'[\xc2\x99]'," ","Hello\xc2There\x99")
Run Code Online (Sandbox Code Playgroud)
打印:'Hello There',不需要的字符替换为空格.
或者,如果每个人都有不同的替换字符:
# remove annoying characters
chars = {
'\xc2\x82' : ',', # High code comma
'\xc2\x84' : ',,', # High code double comma
'\xc2\x85' : '...', # Tripple dot
'\xc2\x88' : '^', # High carat
'\xc2\x91' : '\x27', # Forward single quote
'\xc2\x92' : '\x27', # Reverse single quote
'\xc2\x93' : '\x22', # Forward double quote
'\xc2\x94' : '\x22', # Reverse double quote
'\xc2\x95' : ' ',
'\xc2\x96' : '-', # High hyphen
'\xc2\x97' : '--', # Double hyphen
'\xc2\x99' : ' ',
'\xc2\xa0' : ' ',
'\xc2\xa6' : '|', # Split vertical bar
'\xc2\xab' : '<<', # Double less than
'\xc2\xbb' : '>>', # Double greater than
'\xc2\xbc' : '1/4', # one quarter
'\xc2\xbd' : '1/2', # one half
'\xc2\xbe' : '3/4', # three quarters
'\xca\xbf' : '\x27', # c-single quote
'\xcc\xa8' : '', # modifier - under curve
'\xcc\xb1' : '' # modifier - under line
}
def replace_chars(match):
char = match.group(0)
return chars[char]
return re.sub('(' + '|'.join(chars.keys()) + ')', replace_chars, text)
Run Code Online (Sandbox Code Playgroud)
Gar*_*ees 23
我认为这里存在潜在的问题,调查并解决问题可能是一个好主意,而不是仅仅试图掩盖症状.
\xc2\x95是字符U + 0095的UTF-8编码,它是C1控制字符(MESSAGE WAITING).您的图书馆无法处理它并不奇怪.但问题是,它是如何进入您的数据的?
好吧,一个非常可能的可能性是,它开始于Windows-1252编码中的字符0x95(BULLET),被错误地解码为U + 0095而不是正确的U + 2022,然后编码为UTF-8.(日语术语mojibake描述了这种错误.)
如果这是正确的,那么您可以通过将原始字符放回Windows-1252然后再次正确解码为Unicode来恢复原始字符.(在这些示例中,我使用的是Python 3.3;这些操作在Python 2中有点不同.)
>>> b'\x95'.decode('windows-1252')
'\u2022'
>>> import unicodedata
>>> unicodedata.name(_)
'BULLET'
Run Code Online (Sandbox Code Playgroud)
如果要对0x80-0x99范围内的所有有效Windows-1252字符的字符执行此更正,可以使用以下方法:
def restore_windows_1252_characters(s):
"""Replace C1 control characters in the Unicode string s by the
characters at the corresponding code points in Windows-1252,
where possible.
"""
import re
def to_windows_1252(match):
try:
return bytes([ord(match.group(0))]).decode('windows-1252')
except UnicodeDecodeError:
# No character at the corresponding code point: remove it.
return ''
return re.sub(r'[\u0080-\u0099]', to_windows_1252, s)
Run Code Online (Sandbox Code Playgroud)
例如:
>>> restore_windows_1252_characters('\x95\x99\x85')
'•™…'
Run Code Online (Sandbox Code Playgroud)
Tim*_*ker 11
如果要从字符串中删除所有非ASCII字符,可以使用
text.encode("ascii", "ignore")
Run Code Online (Sandbox Code Playgroud)