gov_commodity_hebei_country.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. from pathlib import Path
  2. import pandas
  3. import pandas as pd
  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. 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. df = get_df(path)
  25. if df is None:
  26. log.info("未找到任何文件")
  27. return None
  28. if year == 2025 and month >= 3:
  29. col_total_index, col_monthly_export_index, col_monthly_import_index = 2, 10, 18
  30. elif year_month in ['2023-02', '2025-01', '2024-01']:
  31. col_total_index, col_monthly_export_index, col_monthly_import_index = 1, 5, 9
  32. else:
  33. col_total_index, col_monthly_export_index, col_monthly_import_index = 1, 9, 17
  34. country_name_index = 1 if year == 2025 and month >= 3 else 0
  35. continue_index = 6
  36. sql_arr = []
  37. sql_arr_copy = []
  38. for index, row in df.iterrows():
  39. if index < continue_index:
  40. continue
  41. country_name = str(row.values[country_name_index]).strip()
  42. if country_name.endswith(")") or country_name.endswith(")"):
  43. country_name = country_name.rsplit("(")[0] or country_name.rsplit("(")[0]
  44. if country_name in EXCLUDE_REGIONS:
  45. continue
  46. country_code = base_country_code.COUNTRY_CODE_MAPPING.get(country_name)
  47. if not country_code:
  48. log.info(f"{year_month} 未找到国家 '{country_name}' 对应国家的编码")
  49. continue
  50. monthly_export, monthly_import, monthly_total = value_row(row, col_total_index, col_monthly_export_index, col_monthly_import_index)
  51. yoy_export, yoy_import, yoy_import_export = 0, 0, 0
  52. if year_month == '2023-02':
  53. # 所有总额除2
  54. monthly_import = round(float(monthly_import) / 2, 4)
  55. monthly_export = round(float(monthly_export) / 2, 4)
  56. monthly_total = round(float(monthly_total) / 2, 4)
  57. sql = (f"INSERT INTO t_yujin_crossborder_prov_country_trade "
  58. 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 "
  59. f"('2023', '2023-01', '130000', '河北省', '{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()) ON DUPLICATE KEY UPDATE create_time = now();\n")
  60. sql_arr_copy.append(sql)
  61. # 组装 SQL 语句
  62. sql = (f"INSERT INTO t_yujin_crossborder_prov_country_trade "
  63. 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 "
  64. f"('{year}', '{year_month}', '130000', '河北省', '{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()) ON DUPLICATE KEY UPDATE create_time = now();\n")
  65. sql_arr.append(sql)
  66. log.info(f"√ {year_month} prov_country_trade 成功生成 SQL 文件 size {len(sql_arr)} ")
  67. # 解析完后生成sql文件批量入库
  68. base_mysql.bulk_insert(sql_arr)
  69. if year_month == '2023-02':
  70. log.info(f"√ {year_month} prov_country_trade 成功生成 SQL 文件 size {len(sql_arr_copy)} ")
  71. base_mysql.bulk_insert(sql_arr_copy)
  72. log.info(f"√ {year_month} prov_country_trade SQL 存表完成!")
  73. def value_row(row,col_total_index, col_monthly_export_index, col_monthly_import_index):
  74. monthly_total = str(row.values[col_total_index]).strip()
  75. monthly_export = str(row.values[col_monthly_export_index]).strip()
  76. monthly_import = str(row.values[col_monthly_import_index]).strip()
  77. return monthly_export, monthly_import, monthly_total
  78. def value_special_handler(value):
  79. if pandas.isna(value) or value == "--" :
  80. return "0"
  81. else:
  82. return value
  83. def hierarchical_traversal(root_path):
  84. root = Path(root_path)
  85. year_dirs = [
  86. item for item in root.iterdir()
  87. if item.is_dir() and base_country_code.YEAR_PATTERN.match(item.name)
  88. ]
  89. for year_dir in sorted(year_dirs, key=lambda x: x.name, reverse=True):
  90. log.info(f"\n年份:{year_dir.name} | 省份:hebei")
  91. month_dirs = []
  92. for item in year_dir.iterdir():
  93. if item.is_dir() and base_country_code.MONTH_PATTERN.match(item.name):
  94. month_dirs.append({"path": item, "month": int(item.name)})
  95. if month_dirs:
  96. for md in sorted(month_dirs, key=lambda x: x["month"], reverse=True):
  97. log.info(f" 月份:{md['month']:02d} | 路径:{md['path']}")
  98. process_folder(md['path'])
  99. if __name__ == '__main__':
  100. hierarchical_traversal(base_country_code.download_dir)
  101. log.info(f"河北石家庄海关国家的所有文件处理完成!")