gov_commodity_jiangsu_country.py 5.5 KB

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