gov_commodity_anhui_import_export.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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. from utils.log import log
  7. CUSTOM_COMMODITY_REPLACEMENTS = {
  8. '家具': '家具及其零件',
  9. '眼镜': '眼镜及其零件',
  10. }
  11. # 需要保留中文括号及内容的商品关键词
  12. PRESERVE_PARENTHESES_KEYWORDS = {
  13. '汽车(包括底盘)',
  14. }
  15. def clean_commodity_name(name, preserve_keywords=None):
  16. """
  17. 自定义清洗商品名称逻辑,支持条件保留中文括号内容
  18. :param name: 商品名称字符串
  19. :param preserve_keywords: 需要保留括号的关键词集合
  20. :return: 清洗后的商品名称
  21. """
  22. name = str(name).strip()
  23. # 去除非必要符号
  24. name = re.sub(r'[#*]', '', name)
  25. # 判断是否需要保留括号内容
  26. if preserve_keywords:
  27. for keyword in preserve_keywords:
  28. if keyword == name:
  29. # 匹配到关键词时,不移除括号内容
  30. return name
  31. # 默认移除中文括号及内容
  32. name = re.sub(r'([^)]*)', '', name)
  33. return name.strip()
  34. def process_folder(path):
  35. file_paths = list(Path(path).glob('*'))
  36. if not file_paths:
  37. log.info("未找到任何文件")
  38. return
  39. year, month = base_country_code.extract_year_month_from_path(path)
  40. import_df = pd.DataFrame()
  41. export_df = pd.DataFrame()
  42. for file in file_paths:
  43. file_path = Path(path) / file
  44. df = pd.read_excel(file_path, header=None).iloc[6:]
  45. value_index = 1 if month == 2 else 3
  46. if "进口商品总值" in file.name:
  47. temp_df = df[[0, value_index]].rename(columns={0: 'commodity', value_index: 'import'})
  48. temp_df['commodity'] = (
  49. temp_df['commodity']
  50. .astype(str)
  51. .apply(lambda x: clean_commodity_name(x, preserve_keywords=PRESERVE_PARENTHESES_KEYWORDS))
  52. .replace(CUSTOM_COMMODITY_REPLACEMENTS, regex=False)
  53. )
  54. temp_df['import'] = pd.to_numeric(temp_df['import'].replace('--', 0), errors='coerce')
  55. # 去重 commodity 列,保留第一个出现的行
  56. temp_df = temp_df.drop_duplicates(subset=['commodity'], keep='first')
  57. import_df = pd.concat([import_df, temp_df])
  58. elif "出口商品总值" in file.name:
  59. temp_df = df[[0, value_index]].rename(columns={0: 'commodity', value_index: 'export'})
  60. temp_df['commodity'] = (
  61. temp_df['commodity']
  62. .astype(str)
  63. .apply(lambda x: clean_commodity_name(x, preserve_keywords=PRESERVE_PARENTHESES_KEYWORDS))
  64. .replace(CUSTOM_COMMODITY_REPLACEMENTS, regex=False)
  65. )
  66. temp_df['export'] = pd.to_numeric(temp_df['export'].replace('--', 0), errors='coerce')
  67. temp_df = temp_df.drop_duplicates(subset=['commodity'], keep='first')
  68. export_df = pd.concat([export_df, temp_df])
  69. save_to_database(import_df, export_df, year, month)
  70. def save_to_database(import_df, export_df, year, month):
  71. # 合并数据(使用outer join保留所有商品)
  72. merged_df = pd.merge(
  73. import_df.groupby('commodity')['import'].sum().reset_index(),
  74. export_df.groupby('commodity')['export'].sum().reset_index(),
  75. on='commodity',
  76. how='outer'
  77. )
  78. year_month = f'{year}-{month:02d}'
  79. processed_commodities = set()
  80. sql_arr = []
  81. sql_arr_copy = []
  82. try:
  83. for _, row in merged_df.iterrows():
  84. commodity_name = str(row['commodity'])
  85. if commodity_name == '肉类' or commodity_name == '其他' or commodity_name == '干鲜瓜果' or commodity_name == '钟表':
  86. log.info(f'{commodity_name} 商品不存在,跳过')
  87. continue
  88. commodity_code, commodity_name_fix = base_mysql.get_commodity_id(commodity_name)
  89. if not commodity_code:
  90. log.info(f"未找到商品名称 '{commodity_name}' 对应的 ID")
  91. continue
  92. if not commodity_name_fix or commodity_name_fix in processed_commodities:
  93. continue
  94. monthly_import = round(row['import'] * 10000, 4)
  95. monthly_export = round(row['export'] * 10000, 4)
  96. monthly_total = round(
  97. (0 if pd.isna(monthly_import) else monthly_import) +
  98. (0 if pd.isna(monthly_export) else monthly_export),
  99. 4
  100. )
  101. if month == 2:
  102. year_month_2 = f'{year}-01'
  103. monthly_import = round(monthly_import / 2, 4)
  104. monthly_export = round(monthly_export / 2, 4)
  105. monthly_total = round(monthly_import + monthly_export, 4)
  106. sql = (f"INSERT INTO t_yujin_crossborder_prov_commodity_trade "
  107. f"(crossborder_year, crossborder_year_month, prov_code, prov_name, commodity_code, commodity_name, monthly_total, monthly_export, monthly_import, create_time) VALUES "
  108. f"('{year}', '{year_month_2}', '340000', '安徽省', '{commodity_code}', '{commodity_name_fix}', {format_sql_value(monthly_total)}, {format_sql_value(monthly_export)}, {format_sql_value(monthly_import)}, now())"
  109. f"ON DUPLICATE KEY UPDATE create_time = now() ;")
  110. sql_arr_copy.append(sql)
  111. sql = (f"INSERT INTO t_yujin_crossborder_prov_commodity_trade "
  112. f"(crossborder_year, crossborder_year_month, prov_code, prov_name, commodity_code, commodity_name, monthly_total, monthly_export, monthly_import, create_time) VALUES "
  113. f"('{year}', '{year_month}', '340000', '安徽省', '{commodity_code}', '{commodity_name_fix}', {format_sql_value(monthly_total)}, {format_sql_value(monthly_export)}, {format_sql_value(monthly_import)}, now())"
  114. f"ON DUPLICATE KEY UPDATE create_time = now() ;")
  115. sql_arr.append(sql)
  116. processed_commodities.add(commodity_name_fix)
  117. # log.info(f'{commodity_name} -> {commodity_name_fix}')
  118. except Exception as e:
  119. log.info(f"{year_month} prov_commodity_trade 生成 SQL 文件时发生异常: {str(e)}")
  120. log.info(f"√ {year_month} prov_commodity_trade 成功生成 SQL 文件 size {len(sql_arr)} ")
  121. # 解析完后生成sql文件批量入库
  122. base_mysql.bulk_insert(sql_arr)
  123. if month == 2:
  124. log.info(f"√ {year_month} prov_commodity_trade copy 成功生成 SQL 文件 size {len(sql_arr_copy)} ")
  125. base_mysql.bulk_insert(sql_arr_copy)
  126. log.info(f"√ {year_month} prov_commodity_trade SQL 存表完成!\n")
  127. def hierarchical_traversal(root_path):
  128. """分层遍历:省份->年份->月目录"""
  129. root = Path(root_path)
  130. # 获取所有年份目录
  131. year_dirs = [
  132. item for item in root.iterdir()
  133. if item.is_dir() and base_country_code.YEAR_PATTERN.match(item.name)
  134. ]
  135. # 按年倒序
  136. for year_dir in sorted(year_dirs, key=lambda x: x.name, reverse=True):
  137. # 构造完整的路径:download/shandong/2025/03
  138. log.info(f"\n年份:{year_dir.name} | 省份:anhui")
  139. # 提取月份目录
  140. month_dirs = []
  141. for item in year_dir.iterdir():
  142. if item.is_dir() and base_country_code.MONTH_PATTERN.match(item.name):
  143. month_dirs.append({
  144. "path": item,
  145. "month": int(item.name)
  146. })
  147. # 按月倒序输出
  148. if month_dirs:
  149. for md in sorted(month_dirs, key=lambda x: x["month"], reverse=True):
  150. log.info(f" 月份:{md['month']:02d} | 路径:{md['path']}")
  151. process_folder(md['path'])
  152. if __name__ == '__main__':
  153. hierarchical_traversal(base_country_code.download_dir)
  154. # root = Path(base_country_code.download_dir)/'2025'/'04'
  155. # process_folder(root)
  156. log.info("安徽合肥海关类章所有文件处理完成!")