gov_commodity_jiangsu_country.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. from pathlib import Path
  2. import pandas as pd
  3. from com.zf.crawl import base_country_code
  4. from com.zf.crawl import base_mysql
  5. # 排除地区名单
  6. EXCLUDE_REGIONS = ["亚洲", "非洲", "欧洲", "拉丁美洲", "北美洲", "大洋洲", "南极洲",
  7. "东南亚国家联盟", "欧洲联盟", "亚太经济合作组织",
  8. "区域全面经济伙伴关系协定(RCEP)成员国", "共建“一带一路”国家和地区"]
  9. def get_df(path):
  10. global df, df_type
  11. file_paths = list(Path(path).glob('*'))
  12. if not file_paths:
  13. print("未找到任何文件")
  14. return
  15. if len(file_paths) == 1:
  16. file_path = file_paths[0]
  17. print(f"处理单文件: {file_path.name}")
  18. xls = pd.ExcelFile(file_path)
  19. sheet_name = base_country_code.find_sheet_by_keyword(file_path, "国别")
  20. if not sheet_name:
  21. print(f"{file_path} 未找到包含 类章 sheet")
  22. return None
  23. df = pd.read_excel(xls, sheet_name=sheet_name, header=None).iloc[5:]
  24. df_type = 0
  25. else:
  26. for file in file_paths:
  27. if "国别" in file.name:
  28. print(f"处理多文件: {file.name}")
  29. file_path = Path(path) / file
  30. df = pd.read_excel(file_path, header=None).iloc[6:]
  31. df_type = 1
  32. break
  33. return df, df_type
  34. def process_folder(path):
  35. year, month = base_country_code.extract_year_month_from_path(path)
  36. year_month = f'{year}-{month:02d}'
  37. sql_arr = []
  38. try:
  39. df, df_type = get_df(path)
  40. if df_type == 0:
  41. country_name_index = 0
  42. col_total_index, col_monthly_export_index, col_monthly_import_index = 1, 3, 5
  43. else:
  44. country_name_index = 1
  45. col_total_index, col_monthly_export_index, col_monthly_import_index = 2, 4, 6
  46. for index, row in df.iterrows():
  47. if index < 4:
  48. continue
  49. # 提取国家名称并去除括号内容
  50. country_name = str(row.values[country_name_index]).strip()
  51. if country_name.endswith(")") or country_name.endswith(")"):
  52. country_name = country_name.rsplit("(")[0] or country_name.rsplit("(")[0]
  53. # 过滤掉排除地区
  54. if country_name in EXCLUDE_REGIONS:
  55. continue
  56. # 获取国家编码
  57. country_code = base_country_code.COUNTRY_CODE_MAPPING.get(country_name)
  58. if not country_code:
  59. print(f"{year_month} 未找到国家 '{country_name}' 对应的编码")
  60. continue
  61. # 提取数据并格式化
  62. monthly_export, monthly_import, monthly_total = value_row(row, col_total_index, col_monthly_export_index, col_monthly_import_index)
  63. if df_type == 0:
  64. monthly_export, monthly_import, monthly_total = round(float(monthly_export) * 10000, 4), round(float(monthly_import) * 10000, 4), round(float(monthly_total) * 10000, 4)
  65. yoy_export, yoy_import, yoy_import_export = 0, 0, 0
  66. # 构建 SQL
  67. sql = (
  68. f"INSERT INTO t_yujin_crossborder_prov_country_trade "
  69. f"(crossborder_year, crossborder_year_month, prov_code, prov_name, country_code, country_name, "
  70. f"monthly_total, monthly_export, monthly_import, yoy_import_export, yoy_import, yoy_export, create_time) "
  71. f"VALUES ('{year}', '{year_month}', '320000', '江苏省', '{country_code}', '{country_name}', "
  72. f"'{monthly_total}', '{monthly_export}', '{monthly_import}', '{yoy_import_export}', '{yoy_import}', "
  73. f"'{yoy_export}', NOW());"
  74. )
  75. sql_arr.append(sql)
  76. except Exception as e:
  77. print(f"{year_month} 处理时发生异常: {str(e)}")
  78. print(f"√ {year_month} 成功生成 SQL 条数: {len(sql_arr)}")
  79. # 批量插入数据库
  80. base_mysql.bulk_insert(sql_arr)
  81. print(f"√ {year_month} prov_country_trade SQL 存表完成!")
  82. def value_row(row, col_total_index, col_monthly_export_index, col_monthly_import_index):
  83. def value_special_handler(value):
  84. if pd.isna(value) or value == "--":
  85. return "0"
  86. else:
  87. return value.strip()
  88. monthly_total = value_special_handler(str(row.values[col_total_index]))
  89. monthly_export = value_special_handler(str(row.values[col_monthly_export_index]))
  90. monthly_import = value_special_handler(str(row.values[col_monthly_import_index]))
  91. return monthly_export, monthly_import, monthly_total
  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("江苏南京海关国别所有文件处理完成!")