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': ''
}
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
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)
df_result.to_excel('./xxx.xlsx',index=False)