gov_commodity_jiangsu_country.py 5.5 KB

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