优化这段代码 import pandas as pd import json # 读取 Excel 文件 df = pd.read_excel("/Users/zhangyuhui/PycharmProjects/NBbank/明细.xlsx") params = { "filepath": "/Users/zhangyuhui/PycharmProjects/NBbank/明细.xlsx", "url": "", "data": { "tranCode": "", "rpaBisAccDtEntitylist": { "bankAcc": "*10272000000746951", "imCustNo": "*1009", "matchCode": "", "accName": "*湄洲东坡餐饮管理(北京)有限公司", "bankName": "*华夏银行", "oppAccNo": "对方账号", "oppAccName": "对方账号名称", "oppAccBank": "对方行名", "cdSign": "", "dbCrFlag": "", "Amt": "", "bal": "账户余额", "bankSerialId": "", "bifCode": "", "Cur": "", "Uses": "摘要", "Abs": "交易描述", "postScript": "", "transTime": "", "voucherNo": "", "voucherType": "", "recTime": "", "transType": "", "accountDate": "", "oppBankAcc": "" } } } rpaBisAccDtEntitylist = [] for index, row in df.iterrows(): dicDt = params['data']['rpaBisAccDtEntitylist'] for key, value in dicDt.items(): if value != '' and not value.startswith('*'): dicDt[key] = row[value] rpaBisAccDtEntitylist.append(dicDt) jsonDt = params['data'] jsonDt['rpaBisAccDtEntitylist'] = rpaBisAccDtEntitylist print(jsonDt)
时间: 2023-07-03 08:05:03 浏览: 166
若依管理存在任何文件读取漏洞检测系统,渗透测试.zip
可以考虑以下优化:
1. 将文件路径定义为一个变量,以便在多个地方使用时进行更改。
2. 将代码封装为一个函数,以便在将来的代码中进行重复使用。
3. 将Excel文件中列的名称与JSON字段的名称进行映射。这样,如果列名或JSON字段名称更改,只需要更改一次映射即可。
优化后的代码如下:
```
import pandas as pd
import json
def process_excel(filepath):
# 读取 Excel 文件
df = pd.read_excel(filepath)
# 定义数据模板
data_template = {
"tranCode": "",
"rpaBisAccDtEntitylist": {
"bankAcc": "*10272000000746951",
"imCustNo": "*1009",
"matchCode": "",
"accName": "*湄洲东坡餐饮管理(北京)有限公司",
"bankName": "*华夏银行",
"oppAccNo": "对方账号",
"oppAccName": "对方账号名称",
"oppAccBank": "对方行名",
"cdSign": "",
"dbCrFlag": "",
"Amt": "",
"bal": "账户余额",
"bankSerialId": "",
"bifCode": "",
"Cur": "",
"Uses": "摘要",
"Abs": "交易描述",
"postScript": "",
"transTime": "",
"voucherNo": "",
"voucherType": "",
"recTime": "",
"transType": "",
"accountDate": "",
"oppBankAcc": ""
}
}
# 定义列名与JSON字段的映射
column_mapping = {
"bankAcc": "bankAcc",
"imCustNo": "imCustNo",
"accName": "accName",
"oppAccNo": "oppAccNo",
"oppAccName": "oppAccName",
"oppAccBank": "oppAccBank",
"bal": "bal",
"Uses": "Uses",
"Abs": "Abs"
}
# 生成 JSON 数据
rpaBisAccDtEntitylist = []
for index, row in df.iterrows():
dicDt = data_template['rpaBisAccDtEntitylist']
for key, value in column_mapping.items():
if value in df.columns and not pd.isnull(row[value]) and not row[value].startswith('*'):
dicDt[key] = row[value]
rpaBisAccDtEntitylist.append(dicDt)
jsonDt = data_template
jsonDt['rpaBisAccDtEntitylist'] = rpaBisAccDtEntitylist
return jsonDt
if __name__ == "__main__":
filepath = "/Users/zhangyuhui/PycharmProjects/NBbank/明细.xlsx"
json_data = process_excel(filepath)
print(json_data)
```
这样,代码更具可读性和可维护性,可以更方便地进行修改和重用。
阅读全文