gov_commodity_anhui_country.py 5.8 KB

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