![](/img/trans.png)
[英]How to return a list of dictionaries from the match of regex.findall?
[英]regex.findall returns a dict instead of list
我正在嘗試從 shell 命令中提取結果。 我需要在 python 中使用 shell 的原因是:因為我需要使用 Golang 二進制文件。
cmd = f'echo {domain} | /root/go/bin/crawler -subd
go-binary crawler
應該 output “一個包含 json 的字符串”。 首先,我需要使用正則表達式從該字符串中提取 json 。
import regex
regu = regex.compile(r'\{(?:[^{}]|(?R))*\}')
cmd = regu.findall(cmd)
主要目標是:從findall
結果中提取 json 值。
cmd = cmd['status']['http']
for i in cmd:
if i['codes']=='200':
stuff
else:
stuff
以上失敗,因為findall
返回一個list
而不是dict
。 作為另一次嘗試,我正在嘗試使用json
pkg 轉儲結果。
import json
dummy = json.dumps(cmd)
cmd = dummy['status']['http']
但是使用json.dumps()
會在每個字符串的前面返回不必要的\
infront。
{\'status':{\'http':{\'codes': \'200'}}}
這意味着我需要使用另一個regex
或其他; 刪除\
。 同時,當使用 findall 時,它會返回:
['{'status':{'http':{'codes':'200'}}}']
我如何將 findall 結果轉換為純dict
以便在使用dummy['status']['http']
時可以提取它?
更新 1:另一種嘗試是使用groupdict
和finditer
:
regu = regex.compile(r'\{(?:[^{}]|(?R))*\}')
cmd = regu.finditer(cmd)
cmd = cmd.groupdict()["statuses"]["http"]
它鑄造了另一個問題。
AttributeError: '_regex.Scanner' object has no attribute 'groupdict'
更新 2:有人可能會對crawler
output 感到好奇:
b'time="2022-08-04" msg="starte"\ntime="2022-08-04" level=dbg msg="finished"\n{"status":{"http":{"codes":200}}}\n'
我不得不使用regex
來刪除所有不必要的評論。
假設 json 在最后一行,並且您的out
被命名為:
import json
cmd = json.loads(out.decode('utf-8').strip().rsplit('\n', 1)[-1])
print(cmd)
output:
{'status': {'http': {'codes': 200}}}
如果您在正則表達式中命名了捕獲組,您只會獲得字典; 這些捕獲將被放入Match
object 的groupdict
屬性中,您可以使用re.search()
或re.finditer()
獲得。 但是你不需要字典。 只需獲取正則表達式的單個匹配項,然后調用json.loads()
將其解析為 JSON。
import regex
regu = regex.compile(r'\{(?:[^{}]|(?R))*\}')
cmd = json.loads(regu.search(cmd).group())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.