gov_commodity_jiangsu_import_export.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. import re
  2. from pathlib import Path
  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. YEAR_PATTERN = re.compile(r"^\d{4}$")
  7. MONTH_PATTERN = re.compile(r"^(0[1-9]|1[0-2])$")
  8. all_records = []
  9. def process_folder(path, all_records):
  10. file_paths = list(Path(path).glob('*'))
  11. if not file_paths:
  12. print("未找到任何文件")
  13. return
  14. year, month = base_country_code.extract_year_month_from_path(path)
  15. year_month = f'{year}-{month:02d}'
  16. if len(file_paths) == 1:
  17. file_path = file_paths[0]
  18. print(f"处理单文件: {file_path.name}")
  19. # 读取所有sheet
  20. xls = pd.ExcelFile(file_path)
  21. import_df = pd.DataFrame()
  22. export_df = pd.DataFrame()
  23. total_df = pd.DataFrame()
  24. sheet_name = base_country_code.find_sheet_by_keyword(file_path, "类章")
  25. if not sheet_name:
  26. print(f"{file_path} 未找到包含 类章 sheet")
  27. return
  28. skip_index = 4 if year_month == '2024-11' else 5
  29. df = pd.read_excel(xls, sheet_name=sheet_name, header=None).iloc[skip_index:]
  30. temp_df = df[[0, 5]].rename(columns={0: 'commodity', 5: 'import'})
  31. temp_df['import'] = pd.to_numeric(temp_df['import'].replace('--', 0), errors='coerce')
  32. temp_df['import'] = temp_df['import'] * 10000
  33. import_df = pd.concat([import_df, temp_df])
  34. temp_df = df[[0, 3]].rename(columns={0: 'commodity', 3: 'export'})
  35. temp_df['export'] = pd.to_numeric(temp_df['export'].replace('--', 0), errors='coerce')
  36. temp_df['export'] = temp_df['export'] * 10000
  37. export_df = pd.concat([export_df, temp_df])
  38. temp_df = df[[0, 1]].rename(columns={0: 'commodity', 1: 'total'})
  39. temp_df['total'] = pd.to_numeric(temp_df['total'].replace('--', 0), errors='coerce')
  40. temp_df['total'] = temp_df['total'] * 10000
  41. total_df = pd.concat([total_df, temp_df])
  42. save_to_database(import_df, export_df, total_df, year, month, all_records)
  43. else: # 2024-10 -2023-01
  44. import_df = pd.DataFrame()
  45. export_df = pd.DataFrame()
  46. total_df = pd.DataFrame()
  47. for file in file_paths:
  48. if "商品类章" in file.name:
  49. print(f"处理多文件: {file.name}")
  50. file_path = Path(path) / file
  51. df = pd.read_excel(file_path, header=None).iloc[6:]
  52. temp_df = df[[1, 5]].rename(columns={1: 'commodity', 5: 'import'})
  53. temp_df['import'] = pd.to_numeric(temp_df['import'].replace('--', 0), errors='coerce')
  54. temp_df['import'] = temp_df['import'] * 10
  55. import_df = pd.concat([import_df, temp_df])
  56. temp_df = df[[1, 3]].rename(columns={1: 'commodity', 3: 'export'})
  57. temp_df['export'] = pd.to_numeric(temp_df['export'].replace('--', 0), errors='coerce')
  58. temp_df['export'] = temp_df['export'] * 10
  59. export_df = pd.concat([export_df, temp_df])
  60. temp_df = df[[1, 2]].rename(columns={1: 'commodity', 2: 'total'})
  61. temp_df['total'] = pd.to_numeric(temp_df['total'].replace('--', 0), errors='coerce')
  62. temp_df['total'] = temp_df['total'] * 10
  63. total_df = pd.concat([total_df, temp_df])
  64. break
  65. save_to_database(import_df, export_df, total_df, year, month, all_records)
  66. def save_to_database(import_df, export_df, total_df, year, month, all_records):
  67. # 直接合并,不使用 groupby,保持原始顺序
  68. merged_df = pd.concat(
  69. [import_df.set_index('commodity'), export_df.set_index('commodity'), total_df.set_index('commodity')], axis=1,
  70. join='outer').reset_index()
  71. merged_df = merged_df
  72. merged_df['original_order'] = merged_df.index # 保留原始顺序
  73. merged_df = merged_df.sort_values('original_order').reset_index(drop=True)
  74. sql_arr = []
  75. processed_commodities = set()
  76. all_records_index = 0
  77. year_month = f'{year}-{month:02d}'
  78. for _, row in merged_df.iterrows():
  79. commodity_name = str(row['commodity'])
  80. # commodity_name = str(row['commodity']).strip()
  81. # 找类名确定索引
  82. result = extract_category_or_chapter(commodity_name, all_records_index)
  83. if result is None:
  84. print(f"未找到商品名称 '{commodity_name}' 对应的ID")
  85. continue
  86. if result >= len(all_records):
  87. print(f"all_records 已超限 '{commodity_name}' 跳过")
  88. continue
  89. all_records_index = result
  90. commodity_code, category_name = int(all_records[all_records_index][0]), str(all_records[all_records_index][1])
  91. if commodity_code in processed_commodities:
  92. continue
  93. monthly_import = round(row['import'], 4)
  94. monthly_export = round(row['export'], 4)
  95. monthly_total = round(row['total'], 4)
  96. sql = (f"INSERT INTO t_yujin_crossborder_prov_commodity_trade "
  97. f"(crossborder_year, crossborder_year_month, prov_code, prov_name, commodity_code, commodity_name, monthly_total, monthly_export, monthly_import, create_time, commodity_source) VALUES "
  98. f"('{year}', '{year_month}', '320000', '江苏省', '{commodity_code}', '{category_name}', {monthly_total}, {monthly_export}, {monthly_import}, now(), 1);")
  99. sql_arr.append(sql)
  100. processed_commodities.add(commodity_code)
  101. print(f"√ {year_month} 成功生成SQL文件 size {len(sql_arr)} ")
  102. base_mysql.bulk_insert(sql_arr)
  103. print(f"√ {year_month} prov_commodity_trade SQL 存表完成!")
  104. def extract_category_or_chapter(text, all_records_index):
  105. text = text.strip()
  106. # 匹配“第一类”或“第1类”
  107. first_class_match = re.match(r'^第(一|\d+)类', text, re.IGNORECASE | re.UNICODE)
  108. if first_class_match and (first_class_match.group(1) == '1' or first_class_match.group(1) == '一'):
  109. return 0
  110. else:
  111. return all_records_index + 1
  112. def hierarchical_traversal(root_path, all_records):
  113. """分层遍历:省份->年份->月目录"""
  114. root = Path(root_path)
  115. # 获取所有年份目录
  116. year_dirs = [
  117. item for item in root.iterdir()
  118. if item.is_dir() and YEAR_PATTERN.match(item.name)
  119. ]
  120. # 按年倒序
  121. for year_dir in sorted(year_dirs, key=lambda x: x.name, reverse=True):
  122. # 构造完整的路径:download/shandong/2025/03
  123. print(f"\n年份:{year_dir.name} | 省份:jiangsu")
  124. # 提取月份目录
  125. month_dirs = []
  126. for item in year_dir.iterdir():
  127. if item.is_dir() and MONTH_PATTERN.match(item.name):
  128. month_dirs.append({
  129. "path": item,
  130. "month": int(item.name)
  131. })
  132. # 按月倒序输出
  133. if month_dirs:
  134. for md in sorted(month_dirs, key=lambda x: x["month"], reverse=True):
  135. print(f" 月份:{md['month']:02d} | 路径:{md['path']}")
  136. process_folder(md['path'], all_records)
  137. if __name__ == '__main__':
  138. all_records = base_mysql.get_hs_all()
  139. hierarchical_traversal(base_country_code.download_dir, all_records)
  140. # root = Path(base_country_code.download_dir)/'2024'/'11'
  141. # process_folder(root, all_records)
  142. print("江苏南京海关类章所有文件处理完成!")