需求:读取下面图1格式的xlsx,将图2里面的SKU_name替换成图一对应标签名称的产品名称,也就是将英文替换成中文,然后将该SKU_name对应的SKU_code替换成图一里的编码
1.
2.
代码如下:
import json
import os
import pandas as pd
xlsx_file_path = "../xml_wen/aaa.xlsx" # xlsx文件的路径
json_file_path = "../niu_zhanggui" # 存放所有json文件的路径
# 使用pandas 读取xlsk文件,返回值为:data = [[],[],[]] 格式
def conversion_xlsx(xlsx_file_path):
df = pd.read_excel(xlsx_file_path)
data = df.values
return data
def get_json_file(json_files_path):
try:
xlsx_data = conversion_xlsx(xlsx_file_path)
all_files = os.listdir(json_files_path)
all_json_file = [i for i in all_files if os.path.splitext(i)[1] == '.json'] # 匹配所有某路径下的json文件,返回list
for json_path in all_json_file:
# 遍历上面获取的list,并获取每个json的绝对路径,进行读取,json路径根据自己情况修改
json_file_base_name = os.path.basename(json_path)
new_base_url = "D:\company\yunliang\work_pro/test/niu_zhanggui"
json_path_name = new_base_url + "/" + json_file_base_name
with open(json_path_name, 'r', encoding="utf8") as f:
data = json.load(f)
# 遍历读取的JSON数据,查找并替换特定的字符串(遍历获取值的过程需根据自己的json数据里的格式及嵌套程度来定义)
for item in data:
for xlsx_obj in xlsx_data:
try:
# 此处是遍历xlsx获取出来的data,进行判断,如果xlsx里的某一列的值是小数,进行转int判断,
# 如果这一列的某行值为空,则自动转为Nan,Nan也是float,所以进行判断,如果是Nan,则pass,不替换对应的SKU_code
if int(xlsx_obj[1]):
code = int(xlsx_obj[1])
except Exception as e:
pass
if str(xlsx_obj[2]) in str(data[item]):
# 将英文名称换成中文,注意:这里换成中文后,对应的字典就变成了str型,根据需求转换(eval)
data[item] = eval(str(data[item]).replace(str(xlsx_obj[2]), xlsx_obj[0]))
# 替换编码,循环sku_obj,判断当前英文名称是否在单个obj的values里,
# 若在,则将该单个obj的sku_code替换成当前编码
img_result = data["ImagesDetectionsResult"]
sku_list = img_result["SKUDetectionsInfo"]
div_obj = img_result["DividedBasketList"]
# 注意:这里的SKU_name已经替换成了中文,所以需拿替换过后的中文来获取对应的SKU_code进行判断、替换
for sku_obj in sku_list:
if xlsx_obj[0] in sku_obj.values():
sku_obj["SKU_code"] = code
for div_obj in div_obj:
basket_list = div_obj["BasketSKUList"]
if len(basket_list) > 0:
for div_backet_obj in basket_list:
if xlsx_obj[0] in div_backet_obj.values():xx
div_backet_obj["SKU_code"] = code
# 将修改后的数据重新写入新的sjon文件x'x
new_base_url = "xxx/new_json"
json_file_base_name = os.path.basename(json_path)
last_path = new_base_url + "/" + json_file_base_name
with open(last_path, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
except Exception as e:
raise e
if __name__ == '__main__':
get_json_file(json_file_path)