首页 > 解决方案 > 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?

标签: python

解决方案


我用以下代码解决了这个问题:

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

推荐阅读