python - DeepSearch - 仅返回索引号
问题描述
我正在使用DeepSearch来查找一个项目并且它有效。我想要的是只返回['members']
. 在这种情况下,ID 是[1]
。关于如何做到这一点的任何想法?
任何帮助将不胜感激,我仍在学习 Python,因此试图解决这些问题。
代码:
from deepdiff import grep
obj = response.json()
item = ".rep"
ds = obj | grep(item, verbose_level=2)
print(ds)
回报:
matched_values': {"root['data'][1]['members'][0]['address']"}}
可以使用正则表达式过滤吗?\D 将过滤为 1 和 0。我将如何删除 0 并只留下 1?
解决方案
我用以下代码解决了这个问题:
import requests
from deepdiff import grep
import re
response = s.get(url)
obj = response.json()
item = ".rep"
ds = obj | grep(item)
print(ds) # {'matched_values': {"root['data'][8]['members'][0]['address']"}}
aa = re.search(r"\d", str(ds))
print(aa) # <re.Match object; span=(34, 35), match='8'>
if aa is not None:
bb = re.findall(r'(\d)', str(ds))
print(bb) # ['8', '0']
if len(bb) == 3: # The list may be three characters total
bb.pop(2) # The third character is not needed
print(bb)
bb = ''.join(str(i) for i in bb[:2]) # convert the list to a string
print(bb)
else:
bb = re.search(r'(\d)', str(ds)) # find only the first int as that's all that's needed
print(format(bb.group(0))) # 8
else:
print('no matches found')
推荐阅读
- java - 如何在 if-else 语句中使用用户输入,如果用户输入不是所要求的,我如何循环代码?
- javascript - 无法将页脚 css 应用于 Angular 应用程序中的页脚对话框
- error-handling - 向最终用户显示或不显示与系统相关的错误消息,这是最佳实践吗?
- python - Python - 如何使用请求和线程循环直到站点关闭
- sorting - 在SAS中合并而不进行proc排序
- python - 如何在 Python 中读取带有标签的 txt 文件?
- asp.net - ASP.NET Webforms OnClientClick 不输入提交
- git - 合并后继续git分支是否常见?
- javascript - 对状态变化做出反应内联样式
- java - 为什么 java.awt.Color 返回 RGB 值?