我正在处理。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()来留下空格和句号?
您可以使用string从字符串中过滤所有不可打印的字符。可打印,如下所示:
>>> s = "somex00string. withx15 funny characters"
>>> import string
>>> printable = set(string.printable)
>>> filter(lambda x: x in printable, s)
'somestring. with funny characters'
字符串。在我的机器上打印包含:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ tnrx0bx0c
编辑:在Python 3中,filter将返回一个可迭代对象。返回字符串的正确方法是:
''.join(filter(lambda x: x in printable, s))
更改为其他编解码器的简单方法是使用encode()或decode()。在您的示例中,您希望转换为ASCII并忽略所有不支持的符号。例如,瑞典字母
>>>s = u'Good bye in Swedish is Hej dxe5'
>>>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 -> str -> unicode
>>> u"hej då".encode("ascii", errors="ignore").decode()
u'hej d'
Python2: str -> unicode -> str(反向解码和编码)
>>> "hej dxe5".decode("ascii", errors="ignore").encode()
'hej d'
根据@artfulrobot,这应该比filter和lambda更快:
import re
re.sub(r'[^x00-x7f]',r'', your-non-ascii-string)
将非ascii字符替换为单个空格
您可以使用以下代码删除非英文字母:
import re
str = "123456790 ABC#%? .(朱惠英)"
result = re.sub(r'[^x00-x7f]',r'', str)
print(result)
返回
123456790 ABC # % ?()
。
你的问题模棱两可;前两个句子放在一起意味着您认为空格和"句号"是非ascii字符。这是不正确的。所有符合ord(char) <= 127的字符都是ASCII字符。例如,您的函数排除了这些字符!"#$%&'()*+,-。/但还包括其他几个,例如[]{}。
请退一步,思考一下,编辑你的问题,告诉我们你想做什么,不提字ASCII,为什么你认为字符这样的字(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()
通过Fluent Python (Ramalho)工作-强烈推荐。受第2章启发的列表理解一行代码:
onlyascii = ''.join([s for s in data if ord(s) < 127])
onlymatch = ''.join([s for s in data if s in
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'])
如果你想要打印ascii字符,你可能应该修改你的代码:
if ord(char) < 32 or ord(char) > 126: return ''
这相当于string.printable
(来自@jterrace的答案),除了没有返回和制表符('t','n','x0b','x0c'和'r'),但不对应于您的问题
这是获得ascii字符和干净代码的最好方法,检查所有可能的错误
from string import printable
def getOnlyCharacters(texts):
_type = None
result = ''
if type(texts).__name__ == 'bytes':
_type = 'bytes'
texts = texts.decode('utf-8','ignore')
else:
_type = 'str'
texts = bytes(texts, 'utf-8').decode('utf-8', 'ignore')
texts = str(texts)
for text in texts:
if text in printable:
result += text
if _type == 'bytes':
result = result.encode('utf-8')
return result
text = '�Ahm�����ed Sheri��'
result = getOnlyCharacters(text)
print(result)
#input --> �Ahm�����ed Sheri��
#output --> Ahmed Sheri