gov_commodity_jiangsu_country.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. from pathlib import Path
  2. import pandas as pd
  3. from utils import base_country_code, base_mysql
  4. from utils.base_country_code import format_sql_value
  5. from utils.log import log
  6. # 排除地区名单
  7. EXCLUDE_REGIONS = ["亚洲", "非洲", "欧洲", "拉丁美洲", "北美洲", "大洋洲", "南极洲",
  8. "东南亚国家联盟", "欧洲联盟", "亚太经济合作组织",
  9. "区域全面经济伙伴关系协定(RCEP)成员国", "共建“一带一路”国家和地区"]
  10. def get_df(path):
  11. global df, df_type
  12. file_paths = list(Path(path).glob('*'))
  13. if not file_paths:
  14. log.info("未找到任何文件")
  15. return
  16. if len(file_paths) == 1:
  17. file_path = file_paths[0]
  18. log.info(f"处理单文件: {file_path.name}")
  19. xls = pd.ExcelFile(file_path)
  20. sheet_name = base_country_code.find_sheet_by_keyword(file_path, "国别")
  21. if not sheet_name:
  22. log.info(f"{file_path} 未找到包含 类章 sheet")
  23. return None
  24. df = pd.read_excel(xls, sheet_name=sheet_name, header=None).iloc[5:]
  25. df_type = 0
  26. else:
  27. for file in file_paths:
  28. if "国别" in file.name:
  29. log.info(f"处理多文件: {file.name}")
  30. file_path = Path(path) / file
  31. df = pd.read_excel(file_path, header=None).iloc[6:]
  32. df_type = 1
  33. break
  34. return df, df_type
  35. def process_folder(path):
  36. year, month = base_country_code.extract_year_month_from_path(path)
  37. year_month = f'{year}-{month:02d}'
  38. sql_arr = []
  39. try:
  40. df, df_type = get_df(path)
  41. if df_type == 0:
  42. country_name_index = 0
  43. col_total_index, col_monthly_export_index, col_monthly_import_index = 1, 3, 5
  44. else:
  45. country_name_index = 1
  46. col_total_index, col_monthly_export_index, col_monthly_import_index = 2, 4, 6
  47. for index, row in df.iterrows():
  48. if index < 4:
  49. continue
  50. # 提取国家名称并去除括号内容
  51. country_name = str(row.values[country_name_index]).strip()
  52. if country_name.endswith(")") or country_name.endswith(")"):
  53. country_name = country_name.rsplit("(")[0] or country_name.rsplit("(")[0]
  54. # 过滤掉排除地区
  55. if country_name in EXCLUDE_REGIONS:
  56. continue
  57. # 获取国家编码
  58. country_code = base_country_code.COUNTRY_CODE_MAPPING.get(country_name)
  59. if not country_code:
  60. log.info(f"{year_month} 未找到国家 '{country_name}' 对应的编码")
  61. continue
  62. # 提取数据并格式化
  63. monthly_export, monthly_import, monthly_total = value_row(row, col_total_index, col_monthly_export_index, col_monthly_import_index)
  64. if df_type == 0:
  65. monthly_export, monthly_import, monthly_total = round(float(monthly_export) * 10000, 4), round(float(monthly_import) * 10000, 4), round(float(monthly_total) * 10000, 4)
  66. yoy_export, yoy_import, yoy_import_export = 0, 0, 0
  67. # 构建 SQL
  68. sql = (
  69. f"INSERT INTO t_yujin_crossborder_prov_country_trade "
  70. f"(crossborder_year, crossborder_year_month, prov_code, prov_name, country_code, country_name, "
  71. f"monthly_total, monthly_export, monthly_import, yoy_import_export, yoy_import, yoy_export, create_time) "
  72. f"VALUES ('{year}', '{year_month}', '320000', '江苏省', '{country_code}', '{country_name}', "
  73. f"{format_sql_value(monthly_total)}, {format_sql_value(monthly_export)}, {format_sql_value(monthly_import)}, '{yoy_import_export}', '{yoy_import}', "
  74. f"'{yoy_export}', NOW());"
  75. )
  76. sql_arr.append(sql)
  77. except Exception as e:
  78. log.info(f"{year_month} 处理时发生异常: {str(e)}")
  79. log.info(f"√ {year_month} 成功生成 SQL 条数: {len(sql_arr)}")
  80. # 批量插入数据库
  81. base_mysql.bulk_insert(sql_arr)
  82. log.info(f"√ {year_month} prov_country_trade SQL 存表完成!")
  83. def value_row(row, col_total_index, col_monthly_export_index, col_monthly_import_index):
  84. def value_special_handler(value):
  85. if pd.isna(value) or value == "--":
  86. return "0"
  87. else:
  88. return value.strip()
  89. monthly_total = value_special_handler(str(row.values[col_total_index]))
  90. monthly_export = value_special_handler(str(row.values[col_monthly_export_index]))
  91. monthly_import = value_special_handler(str(row.values[col_monthly_import_index]))
  92. return monthly_export, monthly_import, monthly_total
  93. def hierarchical_traversal(root_path):
  94. root = Path(root_path)
  95. year_dirs = [
  96. item for item in root.iterdir()
  97. if item.is_dir() and base_country_code.YEAR_PATTERN.match(item.name)
  98. ]
  99. for year_dir in sorted(year_dirs, key=lambda x: x.name, reverse=True):
  100. log.info(f"\n年份:{year_dir.name} | 省份:jiangsu")
  101. month_dirs = []
  102. for item in year_dir.iterdir():
  103. if item.is_dir() and base_country_code.MONTH_PATTERN.match(item.name):
  104. month_dirs.append({"path": item, "month": int(item.name)})
  105. if month_dirs:
  106. for md in sorted(month_dirs, key=lambda x: x["month"], reverse=True):
  107. log.info(f" 月份:{md['month']:02d} | 路径:{md['path']}")
  108. process_folder(md['path'])
  109. if __name__ == '__main__':
  110. hierarchical_traversal(base_country_code.download_dir)
  111. log.info("江苏南京海关国别所有文件处理完成!")