gov_commodity_hebei_country.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. from pathlib import Path
  2. import pandas
  3. import pandas as pd
  4. from hebei import download_dir
  5. from utils import base_country_code, base_mysql
  6. from utils.base_country_code import format_sql_value
  7. from utils.log import log
  8. EXCLUDE_REGIONS = ["亚洲", "非洲", "欧洲", "拉丁美洲", "北美洲", "大洋洲", "南极洲",
  9. "东南亚国家联盟", "欧洲联盟", "亚太经济合作组织",
  10. "区域全面经济伙伴关系协定(RCEP)成员国", "共建“一带一路”国家和地区"]
  11. def get_df(path):
  12. file_paths = list(Path(path).glob('*'))
  13. if not file_paths:
  14. log.info("未找到任何文件")
  15. return None
  16. for file in file_paths:
  17. if "国" in file.name:
  18. log.info(f"处理多文件: {file.name}")
  19. file_path = Path(path) / file
  20. return pd.read_excel(file_path, header=None).iloc[6:]
  21. return None
  22. def process_folder(path):
  23. year, month = base_country_code.extract_year_month_from_path(path)
  24. year_month = f'{year}-{month:02d}'
  25. df = get_df(path)
  26. if df is None:
  27. log.info("未找到任何文件")
  28. return None
  29. if year == 2025 and month >= 3:
  30. col_total_index, col_monthly_export_index, col_monthly_import_index = 2, 10, 18
  31. elif year_month in ['2023-02', '2025-01', '2024-01']:
  32. col_total_index, col_monthly_export_index, col_monthly_import_index = 1, 5, 9
  33. else:
  34. col_total_index, col_monthly_export_index, col_monthly_import_index = 1, 9, 17
  35. country_name_index = 1 if year == 2025 and month >= 3 else 0
  36. continue_index = 6
  37. sql_arr = []
  38. sql_arr_copy = []
  39. for index, row in df.iterrows():
  40. if index < continue_index:
  41. continue
  42. country_name = str(row.values[country_name_index]).strip()
  43. if country_name.endswith(")") or country_name.endswith(")"):
  44. country_name = country_name.rsplit("(")[0] or country_name.rsplit("(")[0]
  45. if country_name in EXCLUDE_REGIONS:
  46. continue
  47. country_code = base_country_code.COUNTRY_CODE_MAPPING.get(country_name)
  48. if not country_code:
  49. log.info(f"{year_month} 未找到国家 '{country_name}' 对应国家的编码")
  50. continue
  51. monthly_export, monthly_import, monthly_total = value_row(row, col_total_index, col_monthly_export_index, col_monthly_import_index)
  52. yoy_export, yoy_import, yoy_import_export = 0, 0, 0
  53. if year_month == '2023-02':
  54. # 所有总额除2
  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. sql = (f"INSERT INTO t_yujin_crossborder_prov_country_trade "
  59. 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 "
  60. 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")
  61. sql_arr_copy.append(sql)
  62. # 组装 SQL 语句
  63. sql = (f"INSERT INTO t_yujin_crossborder_prov_country_trade "
  64. 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 "
  65. 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")
  66. sql_arr.append(sql)
  67. log.info(f"√ {year_month} prov_country_trade 成功生成 SQL 文件 size {len(sql_arr)} ")
  68. # 解析完后生成sql文件批量入库
  69. base_mysql.bulk_insert(sql_arr)
  70. if year_month == '2023-02':
  71. log.info(f"√ {year_month} prov_country_trade 成功生成 SQL 文件 size {len(sql_arr_copy)} ")
  72. base_mysql.bulk_insert(sql_arr_copy)
  73. log.info(f"√ {year_month} prov_country_trade SQL 存表完成!")
  74. def value_row(row,col_total_index, col_monthly_export_index, col_monthly_import_index):
  75. monthly_total = str(row.values[col_total_index]).strip()
  76. monthly_export = str(row.values[col_monthly_export_index]).strip()
  77. monthly_import = str(row.values[col_monthly_import_index]).strip()
  78. return monthly_export, monthly_import, monthly_total
  79. def value_special_handler(value):
  80. if pandas.isna(value) or value == "--" :
  81. return "0"
  82. else:
  83. return value
  84. def hierarchical_traversal(root_path):
  85. root = Path(root_path)
  86. year_dirs = [
  87. item for item in root.iterdir()
  88. if item.is_dir() and base_country_code.YEAR_PATTERN.match(item.name)
  89. ]
  90. for year_dir in sorted(year_dirs, key=lambda x: x.name, reverse=True):
  91. log.info(f"\n年份:{year_dir.name} | 省份:hebei")
  92. month_dirs = []
  93. for item in year_dir.iterdir():
  94. if item.is_dir() and base_country_code.MONTH_PATTERN.match(item.name):
  95. month_dirs.append({"path": item, "month": int(item.name)})
  96. if month_dirs:
  97. for md in sorted(month_dirs, key=lambda x: x["month"], reverse=True):
  98. log.info(f" 月份:{md['month']:02d} | 路径:{md['path']}")
  99. process_folder(md['path'])
  100. if __name__ == '__main__':
  101. hierarchical_traversal(download_dir)
  102. log.info(f"河北石家庄海关国家的所有文件处理完成!")