python:json转dataframe

该代码段展示了如何使用Python遍历指定路径下的PDF文件,获取文件路径,对每个文件进行远程解析并解码中文内容,然后将解析结果构建成DataFrame。最后,将汇总信息导出到Excel表格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# 函数

def get_filename(path,filetype):
    """
    输入:文件夹路径,文件类型
    输出:文件路径,保存在list中
    颗粒度:所有文件路径
    """

    import os

    list_file_path=[]
    for root,dirs,files in os.walk(path):
        for i in files:
            if filetype in i:
                j=path+'/'+i
                list_file_path.append(j) 
    return list_file_path

# 函数

def get_parsing(file_path):
    
    """
    输入:一个文件路径
    输出:解析内容,元素类型是json格式
    颗粒度:一份报告
    """
    import requests
    url = ''
    header = {
        'x-token': ''	# token验证
    }

    params = {'mode': 'xxx', 'cme_parsing': True, 'ocr_required': False}

    pdf_file = {
        'file0': open(file_path, 'rb')
    }
    jsontext_response = requests.post(url, data=params, files=pdf_file, headers=header)
    
    return  jsontext_response

# 函数

def cn_decode(parsing_response):
    """
    输入:解析内容,中文为乱码
    输出:重新编码,显示中文
    颗粒度:一份报告
    """
    jsontext_result=parsing_response.text.encode().decode("unicode_escape")
    return  jsontext_result
# 函数

def create_df_summary(list_jsontext_result):
    
    """
    输入:list类型,元素是重新编码后的解析结果
    输出:json第一/二层内容
    颗粒度:所有报告
    """
    
    import pandas as pd
    import json
    
    df_summary=pd.DataFrame()
    for item in list_jsontext_result:
        temp= pd.read_json(item)
        df_summary=pd.concat([df_summary,temp],axis=0)
    df_summary=df_summary.reset_index(drop=True)
    
    df_summary['CME']=df_summary['result'].map(lambda x:x['CME'])
    df_summary['exception_item_knowledge']=df_summary['result'].map(lambda x:x['exception_item_knowledge'])
    df_summary['imaging_examination']=df_summary['result'].map(lambda x:x['imaging_examination'])
    df_summary['ocr_results']=df_summary['result'].map(lambda x:x['ocr_results'])
    
    return df_summary



def create_df_details(df_summary):
    """
    输入:json第一/二层内容
    输出:json第一/二/三/四层内容
    颗粒度:所有报告
    """
    import pandas as pd
    import json
    
    # 第三层
    
    df_details=pd.DataFrame()

    for i in range(df_summary.shape[0]):

        for item in df_summary['result'][i]["projects"]:
            stringitem = json.dumps(item)
            temp = pd.read_json(stringitem) 
            temp['file']=df_summary['file'][i]
            df_details=pd.concat([df_details,temp],axis=0)

    df_details=df_details.reset_index(drop=True)

    # 第三/四层

    df_details['indicators_name']=df_details['indicators'].map(lambda x:x['indicators_name'])
    df_details['is_new_item']=df_details['indicators'].map(lambda x:x['is_new_item'])
    df_details['range']=df_details['indicators'].map(lambda x:x['range'])
    df_details['unit']=df_details['indicators'].map(lambda x:x['unit'])
    df_details['value']=df_details['indicators'].map(lambda x:x['value'])
    
    
    # 第一/二/三/四层
    df_result=pd.merge(df_summary,df_details,on="file")

    return df_result
# 主程序

# if __name__ == '__main__':

# 参数

path='./xxxx'
path='./test'
filetype='pdf'

list_file_path=get_filename(path,filetype)

list_jsontext_result=[]
for file_path in list_file_path:
    jsontext_response=get_parsing(file_path)
    jsontext_result=cn_decode(jsontext_response)
    list_jsontext_result.append(jsontext_result)

df_summary=create_df_summary(list_jsontext_result)
df_result=create_df_details(df_summary)

# 导出到excel
df_result.to_excel('./xxx.xlsx',index=False)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值