gov_commodity_anhui_country.py 6.0 KB

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