gov_commodity_anhui_country.py 5.9 KB

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