gov_commodity_zhejiang_import_export.py 9.6 KB

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