You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于pool.pm的JSON数据统计Policy频次并导出至Excel?

实现从pool.pm钱包接口统计Policy频次并写入Excel

需求说明

从pool.pm的钱包接口(示例地址:https://pool.pm/wallet/$1111)获取JSON数据,统计所有"policy"字段的重复次数,最终使用openpyxl将结果写入Excel文件,要求第一列为Policy值,第二列为对应频次。

完整实现代码

import requests
from collections import defaultdict
from openpyxl import Workbook

def fetch_wallet_data(wallet_url):
    try:
        # 发送GET请求获取JSON数据
        response = requests.get(wallet_url)
        response.raise_for_status()  # 捕获HTTP请求错误
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"请求数据失败: {e}")
        return None

def count_policy_frequencies(wallet_data):
    policy_counts = defaultdict(int)
    if not wallet_data or 'assets' not in wallet_data:
        print("数据格式异常,未找到assets字段")
        return policy_counts
    
    # 遍历所有资产,统计policy频次
    for asset in wallet_data['assets']:
        if 'policy' in asset:
            policy_counts[asset['policy']] += 1
    return policy_counts

def write_to_excel(policy_counts, output_file='policy_frequencies.xlsx'):
    # 创建工作簿和工作表
    wb = Workbook()
    ws = wb.active
    ws.title = "Policy频次统计"
    
    # 写入表头
    ws.append(["Policy值", "频次"])
    
    # 写入统计结果
    for policy, count in policy_counts.items():
        ws.append([policy, count])
    
    # 保存Excel文件
    try:
        wb.save(output_file)
        print(f"结果已成功写入 {output_file}")
    except Exception as e:
        print(f"写入Excel失败: {e}")

if __name__ == "__main__":
    # 替换为目标钱包的接口地址
    WALLET_URL = "https://pool.pm/wallet/$1111"
    wallet_data = fetch_wallet_data(WALLET_URL)
    if wallet_data:
        policy_counts = count_policy_frequencies(wallet_data)
        write_to_excel(policy_counts)

代码说明

  • 数据获取:fetch_wallet_data函数负责发送HTTP请求,处理请求异常,确保能正确获取接口返回的JSON数据。
  • 频次统计:count_policy_frequencies函数使用defaultdict统计每个policy出现的次数,同时做了数据格式校验,避免因字段缺失导致报错。
  • Excel写入:write_to_excel函数创建Excel工作簿,先写入表头,再遍历统计结果逐行写入,最后保存文件。

使用注意事项

  1. 确保已安装所需依赖包,可通过以下命令安装:
pip install requests openpyxl
  1. 将代码中的WALLET_URL替换为实际需要查询的钱包接口地址。
  2. 如果接口返回的数据结构有变动,需要调整count_policy_frequencies中遍历数据的逻辑,确保能正确定位到policy字段。

内容的提问来源于stack exchange,提问作者Eduardo Duarte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 23:55:22