使用bs4或其他过滤器过滤JSON,并使用openpyxl在Excel中组织

9rygscc1  于 2022-12-15  发布在  其他
关注(0)|答案(2)|浏览(107)

我想从www.example.com过滤一个json文件pool.pm
例如,https://pool.pm/wallet/$1111和我想获取所有“policy”及其重复次数,并使用openpyxl在Excel中组织这些信息,第一列是策略,第二列是重复次数
我拥有的:

import openpyxl
import json
import requests
from bs4 import BeautifulSoup

pooladd = str(input("Insira o address:\t"))

api_pool = "https://pool.pm/wallet/{}"
api_pool2 = api_pool.format(pooladd)
data = requests.get(api_pool2).json()

输出:
| 政策|数量|
| - ------|- ------|
| 48 bbb 7 bbe 9d 59 a40 f1 ce 90 e9 e9 d 0 ff 5002 ec 48 f232 b49 c 0 fb 9a的电子邮件|十个|
| 8728079879 ce 4304 fd 305 b12878 e0 fcea 3b 8a 3a 5435 a21 b5十二月35日上午11时|三个|

mfpqipee

mfpqipee1#

另一个实现!,注解被添加到代码中。构建字典,然后编写excel。

import openpyxl
import json
import requests
from bs4 import BeautifulSoup

pooladd = str(input("Insira o address:\t"))

api_pool = "https://pool.pm/wallet/{}"
api_pool2 = api_pool.format(pooladd)
data = requests.get(api_pool2).json()

policies= [e_tkn['policy'] for e_tkn in data['tokens']]
unique_policies=set(policies)
result={}
for each_policy in unique_policies:
    result[each_policy]=policies.count(each_policy)

result=sorted(((value,key) for (key,value) in result.items()),reverse=True)# sort in decending order, reverse=True
print(result)
from openpyxl import Workbook

wb = Workbook()
ws = wb.active
ws['A1'] = 'Policy' # header
ws['B1'] = 'How Many' # header

row=2
for count,policy in result:
    ws['A' + str(row)]=policy # for each row, for example A2=policy
    ws['B' + str(row)]=count # for each row , for example B2 = count
    row=row+1
    
wb.save('policies.xlsx')
50few1ms

50few1ms2#

我没有看到pandas标记,但如果您感兴趣,下面是value_counts的一种方法:

#pip install pandas
import pandas as pd

out = (
        pd.Series([t["policy"] for t in data["tokens"]])
            .value_counts()
            .to_frame("How Many")
            .reset_index(names="Policy")
      )

如果您想创建Excel电子表格,请使用pandas.DataFrame.to_excel

out.to_excel("output_file.xlsx", sheet_name="test_name", index=False)
#输出:
print(out)
                                                     Policy  How Many
0  f0ff48bbb7bbe9d59a40f1ce90e9e9d0ff5002ec48f232b49ca0fb9a        10
1  8728079879ce4304fd305b12878e0fcea3b8a3a5435a21b5dec35a11         3

相关问题