gov_commodity_hebei_country.py 5.6 KB

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