gov_commodity_jiangsu_import_export.py 7.2 KB

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