gov_commodity_hebei_city.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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. city_code_map = {
  7. "石家庄市": "130100",
  8. "唐山市": "130200",
  9. "秦皇岛市": "130300",
  10. "邯郸市": "130400",
  11. "邢台市": "130500",
  12. "保定市": "130600",
  13. "张家口市": "130700",
  14. "承德市": "130800",
  15. "沧州市": "130900",
  16. "廊坊市": "131000",
  17. "衡水市": "131100",
  18. }
  19. def get_df(path):
  20. file_paths = list(Path(path).glob('*'))
  21. if not file_paths:
  22. print("未找到任何文件")
  23. return None
  24. for file in file_paths:
  25. if "地市" in file.name:
  26. print(f"处理多文件: {file.name}")
  27. file_path = Path(path) / file
  28. return pd.read_excel(file_path, header=None).iloc[5:]
  29. return None
  30. def process_folder(path):
  31. year, month = base_country_code.extract_year_month_from_path(path)
  32. year_month = f'{year}-{month:02d}'
  33. df = get_df(path)
  34. if df is None:
  35. print("未找到任何文件")
  36. return None
  37. if year == 2025 and month >= 3:
  38. col_total_index, col_monthly_export_index, col_monthly_import_index = 2, 10, 18
  39. elif year_month in ['2023-02', '2025-01', '2024-01']:
  40. col_total_index, col_monthly_export_index, col_monthly_import_index = 1, 5, 9
  41. else:
  42. col_total_index, col_monthly_export_index, col_monthly_import_index = 1, 9, 17
  43. country_name_index = 1 if year == 2025 and month >= 3 else 0
  44. sql_arr = []
  45. sql_arr_copy = []
  46. for index, row in df.iterrows():
  47. city_name = str(row.values[country_name_index]).strip()
  48. if city_name.startswith('河北省'):
  49. city_name = city_name.lstrip('河北省')
  50. city_code = city_code_map.get(city_name)
  51. if not city_code:
  52. print(f"未找到省 '{city_name}' 对应市编码")
  53. continue
  54. monthly_export, monthly_import, monthly_total = value_row(row, col_total_index, col_monthly_export_index, col_monthly_import_index)
  55. yoy_export, yoy_import, yoy_import_export = 0, 0, 0
  56. if year_month == '2023-02':
  57. # 所有总额除2
  58. monthly_import = round(float(monthly_import) / 2, 4)
  59. monthly_export = round(float(monthly_export) / 2, 4)
  60. monthly_total = round(float(monthly_total) / 2, 4)
  61. sql_1 = (f"INSERT INTO t_yujin_crossborder_prov_region_trade "
  62. f"(crossborder_year, crossborder_year_month, prov_code, prov_name, city_code, city_name, monthly_total, monthly_export, monthly_import,yoy_import_export, yoy_import, yoy_export, create_time) VALUES "
  63. f"('2023', '2023-01', '130000', '河北省', '{city_code}', '{city_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_copy.append(sql_1)
  65. # 组装 SQL 语句
  66. sql = (f"INSERT INTO t_yujin_crossborder_prov_region_trade "
  67. f"(crossborder_year, crossborder_year_month, prov_code, prov_name, city_code, city_name, monthly_total, monthly_export, monthly_import,yoy_import_export, yoy_import, yoy_export, create_time) VALUES "
  68. f"('{year}', '{year_month}', '130000', '河北省', '{city_code}', '{city_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")
  69. sql_arr.append(sql)
  70. print(f"√ {year_month} prov_region_trade 成功生成 SQL 文件 size {len(sql_arr)} ")
  71. # 解析完后生成sql文件批量入库
  72. base_mysql.bulk_insert(sql_arr)
  73. if year_month == '2023-02':
  74. print(f"√ {year_month} sql_arr_copy 成功生成 SQL 文件 size {len(sql_arr_copy)} ")
  75. base_mysql.bulk_insert(sql_arr_copy)
  76. print(f"√ {year_month} prov_region_trade SQL 存表完成!")
  77. def value_row(row, col_total_index, col_monthly_export_index, col_monthly_import_index):
  78. monthly_total = str(row.values[col_total_index]).strip()
  79. monthly_export = str(row.values[col_monthly_export_index]).strip()
  80. monthly_import = str(row.values[col_monthly_import_index]).strip()
  81. return monthly_export, monthly_import, monthly_total
  82. def value_special_handler(value):
  83. if pandas.isna(value) or value == "--":
  84. return "0"
  85. else:
  86. return value
  87. def hierarchical_traversal(root_path):
  88. root = Path(root_path)
  89. year_dirs = [
  90. item for item in root.iterdir()
  91. if item.is_dir() and base_country_code.YEAR_PATTERN.match(item.name)
  92. ]
  93. for year_dir in sorted(year_dirs, key=lambda x: x.name, reverse=True):
  94. print(f"\n年份:{year_dir.name} | 省份:jiangsu")
  95. month_dirs = []
  96. for item in year_dir.iterdir():
  97. if item.is_dir() and base_country_code.MONTH_PATTERN.match(item.name):
  98. month_dirs.append({"path": item, "month": int(item.name)})
  99. if month_dirs:
  100. for md in sorted(month_dirs, key=lambda x: x["month"], reverse=True):
  101. print(f" 月份:{md['month']:02d} | 路径:{md['path']}")
  102. process_folder(md['path'])
  103. if __name__ == '__main__':
  104. hierarchical_traversal(base_country_code.download_dir)
  105. print(f"河北石家庄海关城市所有文件处理完成!")