gov_commodity_zhejiang_import_export.py 9.0 KB

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