86 python unicode text ascii filter
我正在使用.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
Run Code Online (Sandbox Code Playgroud)
我应该如何修改onlyascii()以留出空格和句点?我想这不是太复杂但我无法弄明白.
jte*_*ace 163
您可以使用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'
Run Code Online (Sandbox Code Playgroud)
我的机器上的string.printable包含:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c
Run Code Online (Sandbox Code Playgroud)
Zwe*_*end 81
更改为不同编解码器的简单方法是使用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
Run Code Online (Sandbox Code Playgroud)
编辑:
Python3:str - > bytes - > str
>>>"Hej då".encode("ascii", errors="ignore").decode()
'hej d'
Run Code Online (Sandbox Code Playgroud)
Python2:unicode - > str - > unicode
>>> u"hej då".encode("ascii", errors="ignore").decode()
u'hej d'
Run Code Online (Sandbox Code Playgroud)
Python2:str - > unicode - > str(以相反的顺序解码和编码)
>>> "hej d\xe5".decode("ascii", errors="ignore").encode()
'hej d'
Run Code Online (Sandbox Code Playgroud)
Noa*_*nos 26
根据@artfulrobot,这应该比filter和lambda更快:
re.sub(r'[^\x00-\x7f]',r'', your-non-ascii-string)
Run Code Online (Sandbox Code Playgroud)
你的问题含糊不清; 前两个句子一起表示你认为空格和"句号"是非ASCII字符.这是不正确的.ord(char)<= 127的所有字符都是ASCII字符.例如,你的函数排除了这些字符!"#$%&\'()*+, - ./但包含其他几个例如[] {}.
请退后一步,想一想,编辑你的问题,告诉我们你要做什么,不提ASCII字,以及为什么你认为ord(char)> = 128这样的字符是可以忽略的.另外:哪个版本的Python?输入数据的编码是什么?
请注意,您的代码将整个输入文件作为单个字符串读取,而您对另一个答案的评论("出色的解决方案")意味着您不关心数据中的换行符.如果您的文件包含两行,如下所示:
this is line 1
this is line 2
Run Code Online (Sandbox Code Playgroud)
结果将是'this is line 1this is line 2'......你真正想要的是什么?
更好的解决方案包括:
onlyascii 认识到如果要保留参数,过滤函数只需要返回一个真值:
def filter_func(char):
return char == '\n' or 32 <= ord(char) <= 126
# and later:
filtered_data = filter(filter_func, data).lower()
Run Code Online (Sandbox Code Playgroud)您可以使用以下代码删除非英文字母:
import re
str = "123456790 ABC#%? .(???)"
result = re.sub(r'[^\x00-\x7f]',r'', str)
print(result)
Run Code Online (Sandbox Code Playgroud)
这将返回
123456790 ABC#%?.()
| 归档时间: |
|
| 查看次数: |
155347 次 |
| 最近记录: |