所以基本上,我试图编写一个过滤器,我可以从字典中分隔数字和字母,并在它们之间留一个空格。例如12346 S
12346 Q
。
def check_if_works():
dict_info = {}
dict_info['1234'] = "test"
dict_info['12456s'] = "test"
dict_info['12456q'] = "test"
dict_info['12456b'] = "test"
dict_info['123456'] = "test"
dict_info['asdftes'] = "test"
dict_info['asdftess'] = "test"
dict_info['asdftessd'] = "test"
arr = []
for key,value in dict_info.iteritems():
if key.isalpha() or key.isdigit():
pass
#print key
else:
print key
答案 0 :(得分:0)
不需要字典列表,您想直接填写并转储new_dict。
此外,不需要try / except(由于str.isalpha()
永远不会抛出异常,因此不起作用),您应该组合检查以测试它只包含字母或数字(isalnum()
)并且它不仅包含字母(isalpha()
)或仅包含数字(isdigit()
)。
然后,您也不会在每个迭代步骤中对原始字典执行一次文件,但最后只能翻译一次以转储整个结果字典。
new_dict = {}
for key,value in dict_info.iteritems():
check = key.isalnum() and not (key.isalpha() or key.isdigit())
new_dict[insert_spaces(key)] = value
print (key, ":", value)
with open('output.json', 'wb') as outfile:
json.dump(new_dict, outfile, indent=4)
您需要在数字+字母或字母+数字之间插入空格的函数insert_spaces
如下所示:
import re
def insert_spaces(key):
return re.sub(r'(\D)(\d)', r"\1 \2", re.sub(r'(\d)(\D)', r"\1 \2", key))
或者你可以用字典理解替换整个代码(自Python 2.7起):
with open('output.json', 'wb') as outfile:
json.dump({ insert_spaces(key): dict_info[key] for key in dict_info if key.isalnum() and not (key.isalpha() or key.isdigit()) }, outfile, indent=4)
或者通过将检查条件提取到lambda函数来格式化:
check_key = lambda key: key.isalnum() and not (key.isalpha() or key.isdigit())
with open('output.json', 'wb') as outfile:
json.dump({ insert_spaces(k): dict_info[k] for k in dict_info if check_key(k) },
outfile, indent=4)