如何去除非ASCII字符但保留句点和空格?
我正在处理一个.txt文件。我想从这个文件中提取一段文本,要求里面没有非ASCII字符。不过,我希望保留空格和句号。目前,我的代码也把它们去掉了。以下是我的代码:
def onlyascii(char):
if ord(char) < 48 or ord(char) > 127: return ''
else: return char
def get_my_string(file_path):
f=open(file_path,'r')
data=f.read()
f.close()
filtered_data=filter(onlyascii, data)
filtered_data = filtered_data.lower()
return filtered_data
我应该怎么修改onlyascii()这个函数,才能保留空格和句号呢?我觉得这应该不太复杂,但我就是想不出来。
8 个回答
42
根据@artfulrobot的说法,这种方法应该比使用filter和lambda更快:
import re
re.sub(r'[^\x00-\x7f]',r'', your-non-ascii-string)
这里有更多的例子 用一个空格替换非ASCII字符
119
要换成不同的编码方式,其实很简单,可以用 encode() 或 decode() 这两个方法。在你的情况中,你想把内容转换成 ASCII 编码,并且忽略掉所有不支持的符号。比如,瑞典字母 å 就不是 ASCII 字符:
>>>s = u'Good bye in Swedish is Hej d\xe5'
>>>s = s.encode('ascii',errors='ignore')
>>>print s
Good bye in Swedish is Hej d
补充:
在 Python3 中:字符串(str)变成字节(bytes),再变回字符串(str)
>>>"Hej då".encode("ascii", errors="ignore").decode()
'hej d'
在 Python2 中:Unicode(unicode)变成字符串(str),再变回 Unicode(unicode)
>>> u"hej då".encode("ascii", errors="ignore").decode()
u'hej d'
在 Python2 中:字符串(str)变成 Unicode(unicode),再变回字符串(str)(解码和编码的顺序相反)
>>> "hej d\xe5".decode("ascii", errors="ignore").encode()
'hej d'
229
你可以使用 string.printable 来过滤掉字符串中所有不可打印的字符,方法如下:
>>> s = "some\x00string. with\x15 funny characters"
>>> import string
>>> printable = set(string.printable)
>>> filter(lambda x: x in printable, s)
'somestring. with funny characters'
在我的电脑上,string.printable 包含以下内容:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c
补充说明:在 Python 3 中,filter 函数会返回一个可迭代的对象。如果想要得到一个字符串,可以这样做:
''.join(filter(lambda x: x in printable, s))