简体   繁体   English

如何从Python字典中删除非ASCII字符并替换为空格

[英]How to remove from Python Dictionary Non ASCII characters and replacing with spaces

I have dictionary 我有字典

a = {'age': '12\xa0', 'name': 'pks\xa0\xa0'}

I wanted to remove all Non ASCII characters and replace with spaces. 我想删除所有非ASCII字符并替换为空格。

For Removing Non ASCII character in non-dict we are using 对于我们正在使用的非dict中删除非ASCII字符

''.join([i if 32 < ord(i) < 126 else " " for i in a])

But how to use for dictionary. 但如何使用字典。 Any help would be appreciated. 任何帮助,将不胜感激。

You don't need a list comprehension and ord just encode to ascii and ignore the errors: 您不需要列表推导, ord只需编码为ascii并忽略错误:

In [106]: {key:value.encode('ascii',errors='ignore') for key, value in a.items()}
Out[106]: {'age': b'12', 'name': b'pks'}

If you want to replace with space here is an efficient way: 如果你想用空格替换这里是一种有效的方法:

In [117]: def replace_nonascii(mydict):
              for key, value in a.items():
                  new = value.encode('ascii',errors='ignore')
                  yield key, new + b' ' * (len(value) - len(new))
   .....:         

In [118]: dict(replace_nonascii(a))
Out[118]: {'age': b'12 ', 'name': b'pks  '}

Building on the answer from this question , you can use re.sub , removing non-ASCII characters and replacing them with a space. 基于此问题的答案,您可以使用re.sub ,删除非ASCII字符并用空格替换它们。

>>> import re
>>> {k : re.sub(r'[^\x00-\x7F]',' ', v) for k, v in a.items()}
{'age': '12 ', 'name': 'pks  '}

This should work on python-3.x (python) as well as python-2.x (pyth off ). 这应该适用于python-3.x(python)以及python-2.x(pyth off )。

You can remove the non printable ascii chars like this; 你可以删除这样的不可打印的ascii字符; it applies the line of code you provided to replace non printable ascii by a white space, to each value in the dictionary: 它将您提供的代码行应用于将不可打印的ascii替换为空格,并应用于字典中的每个值:

def remove_non_printable_ascii(s):
    return ''.join([c if 32 < ord(c) < 127 else " " for c in s])

a = {'age': '12\xa0', 'name': 'pks\xa0\xa0'}

for k in a:
    a[k] = remove_non_printable_ascii(a[k])

a

output: 输出:

{'age': '12 ', 'name': 'pks  '}

Iteration on dictionary with map can be used: 可以使用带有map字典迭代:

for k,v in a.items():
    a[k] = "".join(map(lambda c: c if 32<ord(c)<127 else " " , v))

print(a) give following output: print(a)给出以下输出:

{'name': 'pks  ', 'age': '12 '}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM