gov_commodity_zhejiang_import_export.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. from pathlib import Path
  2. import re
  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. '有机发光二极管平板显示模组': '有机发光二极管(OLED)平板显示模组',
  10. }
  11. PRESERVE_PARENTHESES_KEYWORDS = {
  12. '汽车(包括底盘)',
  13. }
  14. def clean_commodity_name(name, preserve_keywords=None):
  15. """
  16. 自定义清洗商品名称逻辑,支持条件保留中文括号内容
  17. :param name: 商品名称字符串
  18. :param preserve_keywords: 需要保留括号的关键词集合
  19. :return: 清洗后的商品名称
  20. """
  21. name = str(name).strip().replace('(', '(').replace(')', ')')
  22. # 去除非必要符号
  23. name = re.sub(r'[#*?]', '', name)
  24. name = re.sub(r'_x000D_', '', 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 get_df_import_export(path, year_month):
  35. file_paths = list(Path(path).glob('*'))
  36. if not file_paths:
  37. log.info("未找到任何文件")
  38. return None
  39. file_path = file_paths[0]
  40. log.info(f"处理文件: {file_path.name}")
  41. xls = pd.ExcelFile(file_path)
  42. import_df = pd.DataFrame()
  43. export_df = pd.DataFrame()
  44. flag = True
  45. sheet_name = base_country_code.find_sheet_by_keyword(file_path, "主出商品")
  46. if not sheet_name:
  47. log.info(f"{file_path} 单文件未找到包含 主出商品 sheet")
  48. # 23年1-11月数据要在多文件里找
  49. for file_path in file_paths:
  50. if '主要出口商品' in file_path.name:
  51. file_path = file_path
  52. flag = False
  53. break
  54. if not sheet_name and flag:
  55. log.info(f"{path} 中未找到 主出商品 sheet或文件")
  56. return None
  57. if flag:
  58. df = pd.read_excel(xls, sheet_name=sheet_name, header=None).iloc[2:]
  59. else:
  60. df = pd.read_excel(file_path, header=None).iloc[1:]
  61. temp_df = df[[0, 1]].rename(columns={0: 'commodity', 1: 'export'})
  62. temp_df['commodity'] = (
  63. temp_df['commodity']
  64. .astype(str)
  65. .apply(lambda x: clean_commodity_name(x, preserve_keywords=PRESERVE_PARENTHESES_KEYWORDS))
  66. .replace(CUSTOM_COMMODITY_REPLACEMENTS, regex=False)
  67. )
  68. temp_df['export'] = pd.to_numeric(temp_df['export'].replace('--', 0), errors='coerce').astype(float)
  69. if year_month and year_month == '2024-07':
  70. temp_df['export'] = temp_df['export'] / 10000
  71. export_df = pd.concat([export_df, temp_df])
  72. flag_2 = True
  73. sheet_name = base_country_code.find_sheet_by_keyword(file_path, "主进商品")
  74. if not sheet_name:
  75. log.info(f"{file_path} 单文件未找到包含 主进商品 sheet")
  76. # 23年1-11月数据要在多文件里找
  77. for file_path in file_paths:
  78. if '主要进口商品' in file_path.name:
  79. file_path = file_path
  80. flag_2 = False
  81. break
  82. if not sheet_name and flag_2:
  83. log.info(f"{path} 中未找到 主进商品 sheet或文件")
  84. return None
  85. if flag_2:
  86. df = pd.read_excel(xls, sheet_name=sheet_name, header=None).iloc[2:]
  87. else:
  88. df = pd.read_excel(file_path, header=None).iloc[1:]
  89. temp_df = df[[0, 1]].rename(columns={0: 'commodity', 1: 'import'})
  90. temp_df['commodity'] = (
  91. temp_df['commodity']
  92. .astype(str)
  93. .apply(lambda x: clean_commodity_name(x, preserve_keywords=PRESERVE_PARENTHESES_KEYWORDS))
  94. .replace(CUSTOM_COMMODITY_REPLACEMENTS, regex=False)
  95. )
  96. temp_df['import'] = pd.to_numeric(temp_df['import'].replace('--', 0), errors='coerce').astype(float)
  97. if year_month and year_month == '2024-07':
  98. temp_df['import'] = temp_df['import'] / 10000
  99. import_df = pd.concat([import_df, temp_df])
  100. return import_df, export_df
  101. def process_folder(path):
  102. res = get_df_import_export(path, None)
  103. if not res:
  104. log.info(f"{path} 目录里文件未找到包含 主出、主进商品 sheet")
  105. return
  106. import_df, export_df = res
  107. year, month = base_country_code.extract_year_month_from_path(path)
  108. year_month = f'{year}-{month:02d}'
  109. # 当月数据分组清洗
  110. curr_import = import_df.groupby('commodity')['import'].sum().reset_index()
  111. curr_export = export_df.groupby('commodity')['export'].sum().reset_index()
  112. if not month == 1:
  113. previous_month_dir = base_country_code.get_previous_month_dir(path)
  114. res = get_df_import_export(previous_month_dir, year_month)
  115. if not res:
  116. log.info(f"{path} 上月目录里文件未找到包含 主出、主进商品 sheet")
  117. return
  118. prev_import_df, prev_export_df = res
  119. # 上月数据分组
  120. prev_import = prev_import_df.groupby('commodity')['import'].sum().reset_index()
  121. prev_export = prev_export_df.groupby('commodity')['export'].sum().reset_index()
  122. # 差值计算
  123. curr_import = pd.merge(curr_import, prev_import, on='commodity', how='left')
  124. curr_import['import'] = round(curr_import['import_x'] - curr_import['import_y'], 4)
  125. curr_export = pd.merge(curr_export, prev_export, on='commodity', how='left')
  126. curr_export['export'] = round(curr_export['export_x'] - curr_export['export_y'], 4)
  127. log.info(f"合并文件: {path}*********{previous_month_dir}")
  128. # 合并进出口数据
  129. merged_df = pd.merge(curr_import, curr_export, on='commodity', how='outer')
  130. save_to_database(merged_df, year, month)
  131. def save_to_database(merged_df, year, month):
  132. year_month = f'{year}-{month:02d}'
  133. processed_commodities = set()
  134. sql_arr = []
  135. try:
  136. for _, row in merged_df.iterrows():
  137. commodity_name = str(row['commodity']).strip()
  138. if commodity_name == '消费品' or commodity_name == '劳动密集型产品':
  139. log.info(f'{commodity_name} 商品不存在,跳过')
  140. continue
  141. commodity_code, commodity_name_fix = base_mysql.get_commodity_id(commodity_name)
  142. if not commodity_code:
  143. log.info(f"未找到商品名称 '{commodity_name}' 对应的 ID")
  144. continue
  145. if not commodity_name_fix or commodity_name_fix in processed_commodities:
  146. log.info(f"已处理过 '{commodity_name_fix}',传入name:{commodity_name}")
  147. continue
  148. if year == 2025 or (year == 2024 and month in [7, 8, 9, 10, 11, 12]):
  149. monthly_import = round(row['import'], 4)
  150. monthly_export = round(row['export'], 4)
  151. monthly_total = round(
  152. (0 if pd.isna(monthly_import) else monthly_import) +
  153. (0 if pd.isna(monthly_export) else monthly_export),
  154. 4
  155. )
  156. else:
  157. monthly_import = round(row['import'] / 10000, 4)
  158. monthly_export = round(row['export'] / 10000, 4)
  159. monthly_total = round(
  160. (0 if pd.isna(monthly_import) else monthly_import) +
  161. (0 if pd.isna(monthly_export) else monthly_export),
  162. 4
  163. )
  164. sql = (f"INSERT INTO t_yujin_crossborder_prov_commodity_trade "
  165. f"(crossborder_year, crossborder_year_month, prov_code, prov_name, commodity_code, commodity_name, monthly_total, monthly_export, monthly_import, create_time) VALUES "
  166. f"('{year}', '{year_month}', '330000', '浙江省', '{commodity_code}', '{commodity_name_fix}', {format_sql_value(monthly_total)}, {format_sql_value(monthly_export)}, {format_sql_value(monthly_import)}, now());")
  167. sql_arr.append(sql)
  168. processed_commodities.add(commodity_name_fix)
  169. # log.info(f'{commodity_name} -> {commodity_name_fix}')
  170. except Exception as e:
  171. log.info(f"{year_month} prov_commodity_trade 生成 SQL 文件时发生异常: {str(e)}")
  172. log.info(f"√ {year_month} prov_commodity_trade 成功生成 SQL 文件 size {len(sql_arr)} ")
  173. # 解析完后生成sql文件批量入库
  174. base_mysql.bulk_insert(sql_arr)
  175. log.info(f"√ {year_month} prov_commodity_trade SQL 存表完成!\n")
  176. def hierarchical_traversal(root_path):
  177. """分层遍历:省份->年份->月目录"""
  178. root = Path(root_path)
  179. # 获取所有年份目录
  180. year_dirs = [
  181. item for item in root.iterdir()
  182. if item.is_dir() and base_country_code.YEAR_PATTERN.match(item.name)
  183. ]
  184. # 按年倒序
  185. for year_dir in sorted(year_dirs, key=lambda x: x.name, reverse=True):
  186. log.info(f"\n年份:{year_dir.name} | 省份:jiangsu")
  187. # 提取月份目录
  188. month_dirs = []
  189. for item in year_dir.iterdir():
  190. if item.is_dir() and base_country_code.MONTH_PATTERN.match(item.name):
  191. month_dirs.append({
  192. "path": item,
  193. "month": int(item.name)
  194. })
  195. # 按月倒序输出
  196. if month_dirs:
  197. for md in sorted(month_dirs, key=lambda x: x["month"], reverse=True):
  198. log.info(f" 月份:{md['month']:02d} | 路径:{md['path']}")
  199. process_folder(md['path'])
  200. if __name__ == '__main__':
  201. hierarchical_traversal(base_country_code.download_dir)
  202. # root = Path(base_country_code.download_dir)/'2023'/'01'
  203. # process_folder(root)
  204. log.info("浙江杭州海关类章所有文件处理完成!")