我怎样才能删除 ASCII 字符,但留下积分和空格 Python?

我与文件一起工作 .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//, 留下空间和积分? 我认为这不是太难,但我无法理解它。
已邀请:

裸奔

赞同来自:

您可以从无法使用无法打印的字符串中过滤所有字符
http://docs.python.org/library ... table
, 例如::


>>> 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

快网

赞同来自:

轻松去另一个编解码器的方法是使用 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 - > 字节 - > str


>>>"Hej då".encode/"ascii", errors="ignore"/.decode//
'hej d'


Python2: unicode - > str - > unicode


>>> u"hej då".encode/"ascii", errors="ignore"/.decode//
u'hej d'


Python2: str - > unicode - > str /以相反的顺序解码和编码/


>>> "hej d\xe5".decode/"ascii", errors="ignore"/.encode//
'hej d'

奔跑吧少年

赞同来自:

根据 @artfulrobot, 它应该比过滤器更快 lambda:


re.sub/r'[^\x00-\x7f]',r'', your-non-ascii-string/


在这里查看更多例子。
https://coderoad.ru/20078816/

知食

赞同来自:

你的问题含糊不清; 前两个建议在一起,意味着你认为差距和 "period" 不是符号 ASCII. 这不是真的。 所有符号都这样 ord /char/ <= 127 是 ASCII 符号。 例如,您的函数消除了这些字符。 !"#$%&\'//*+,-./ 但包括其他几个其他人 []{}.

请退后一步,想一想一下并编辑你的问题,告诉我们你想要做什么,没有提到这个词 ASCII, 为什么你认为符号是这样的 ord/char/ >= 128 忽视。 还有:什么版本 Python? 输入数据的编码是什么?

请注意,您的代码将整个输入文件读为一行,以及您的评论 /"完美的解决方案"/ 另一个答案意味着您不关心数据中的新行。 如果您的文件包含两行:


this is line 1
this is line 2


结果,事实证明
'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//

龙天

赞同来自:

您可以使用以下代码删除非英文字母:


import re
str = "123456790 ABC#%? ./朱惠英/"
result = re.sub/r'[^\x00-\x7f]',r'', str/
print/result/


这将回来

123456790 ABC#%? .//

喜特乐

赞同来自:

如果你想打印 ascii 符号,您可能需要修复您的代码:


if ord/char/ < 32 or ord/char/ > 126: return ''


这是相同的
string.printable

/回答 @jterrace/, 除了缺乏回报和标签 /'\t', '\n', '\x0b', '\x0c ' 和 '\r'/, 但与您的问题的范围不符。

莫问

赞同来自:

我们通过你的方式 Fluent Python /Ramalho/ - 极力推荐。
理解列表 one-ish-liners 受到头部的启发 2:


onlyascii = ''.join/[s for s in data if ord/s/ < 127]/
onlymatch = ''.join/[s for s in data if s in
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz']/

要回复问题请先登录注册