gov_commodity_hebei_import_export.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. from pathlib import Path
  2. import pandas as pd
  3. import re
  4. from utils.log import log
  5. from utils import base_country_code, base_mysql
  6. from utils.base_country_code import format_sql_value
  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 process_folder(path):
  35. year, month = base_country_code.extract_year_month_from_path(path)
  36. name_index = 1 if year == 2025 and month >= 3 else 0
  37. value_index = 5 if year == 2025 and month >= 3 else 4
  38. res = df_data(path, name_index, value_index)
  39. if not res:
  40. log.info(f"{path} 上月目录里文件未找到包含 主出、主进商品 sheet")
  41. return
  42. export_df, import_df = res
  43. merged_df = pd.merge(
  44. import_df.groupby('commodity')['import'].sum().reset_index() if not import_df.empty else pd.DataFrame(columns=['commodity', 'import']),
  45. export_df.groupby('commodity')['export'].sum().reset_index() if not export_df.empty else pd.DataFrame(columns=['commodity', 'export']),
  46. on='commodity',
  47. how='outer'
  48. ).infer_objects()
  49. save_to_database(merged_df, year, month)
  50. def save_to_database(merged_df, year, month):
  51. processed_commodities = set()
  52. sql_arr = []
  53. sql_arr_copy = []
  54. year_month = f'{year}-{month:02d}'
  55. try:
  56. for _, row in merged_df.iterrows():
  57. commodity_name = str(row['commodity']).strip()
  58. commodity_code,commodity_name_fix = base_mysql.get_commodity_id(commodity_name)
  59. if not commodity_code:
  60. log.info(f"未找到商品名称 '{commodity_name}' 对应的 ID")
  61. continue
  62. if not commodity_name_fix or commodity_name_fix in processed_commodities:
  63. continue
  64. monthly_import = round(row['import'], 4)
  65. monthly_export = round(row['export'], 4)
  66. monthly_total = round(
  67. (0 if pd.isna(monthly_import) else monthly_import) +
  68. (0 if pd.isna(monthly_export) else monthly_export),
  69. 4
  70. )
  71. if year_month == '2023-02':
  72. monthly_import = round(monthly_import / 2, 4)
  73. monthly_export = round(monthly_export / 2, 4)
  74. monthly_total = round(monthly_import + monthly_export, 4)
  75. sql = (f"INSERT INTO t_yujin_crossborder_prov_commodity_trade "
  76. f"(crossborder_year, crossborder_year_month, prov_code, prov_name, commodity_code, commodity_name, monthly_total, monthly_export, monthly_import, create_time) VALUES "
  77. f"('2023', '2023-01', '130000', '河北省', '{commodity_code}', '{commodity_name_fix}', {format_sql_value(monthly_total)}, {format_sql_value(monthly_export)}, {format_sql_value(monthly_import)}, now())"
  78. f"ON DUPLICATE KEY UPDATE create_time = now() ;")
  79. sql_arr_copy.append(sql)
  80. sql = (f"INSERT INTO t_yujin_crossborder_prov_commodity_trade "
  81. f"(crossborder_year, crossborder_year_month, prov_code, prov_name, commodity_code, commodity_name, monthly_total, monthly_export, monthly_import, create_time) VALUES "
  82. f"('{year}', '{year_month}', '130000', '河北省', '{commodity_code}', '{commodity_name_fix}', {format_sql_value(monthly_total)}, {format_sql_value(monthly_export)}, {format_sql_value(monthly_import)}, now())"
  83. f"ON DUPLICATE KEY UPDATE create_time = now() ;")
  84. sql_arr.append(sql)
  85. processed_commodities.add(commodity_name_fix)
  86. except Exception as e:
  87. log.info(f"{year_month} prov_commodity_trade 生成 SQL 文件时发生异常: {str(e)}")
  88. log.info(f"√ {year_month} prov_commodity_trade 成功生成 SQL 文件 size {len(sql_arr)} ")
  89. # 解析完后生成sql文件批量入库
  90. base_mysql.bulk_insert(sql_arr)
  91. if year_month == '2023-02':
  92. log.info(f"√ {year_month} prov_commodity_trade copy 成功生成 SQL 文件 size {len(sql_arr_copy)} ")
  93. base_mysql.bulk_insert(sql_arr_copy)
  94. log.info(f"√ {year_month} prov_commodity_trade SQL 存表完成!")
  95. def df_data(path, name_index, value_index):
  96. file_paths = list(Path(path).glob('*'))
  97. if not file_paths:
  98. log.info("未找到任何文件")
  99. return None
  100. import_df = pd.DataFrame()
  101. export_df = pd.DataFrame()
  102. for file_path in file_paths:
  103. if '出口' in file_path.name:
  104. df = pd.read_excel(file_path, header=None).iloc[5:]
  105. temp_df = df[[name_index, value_index]].rename(columns={name_index: 'commodity', value_index: 'export'})
  106. # temp_df['commodity'] = temp_df['commodity'].str.replace(r'[*#]', '', regex=True)
  107. temp_df['commodity'] = (
  108. temp_df['commodity']
  109. .astype(str)
  110. .apply(lambda x: clean_commodity_name(x, preserve_keywords=PRESERVE_PARENTHESES_KEYWORDS))
  111. .replace(CUSTOM_COMMODITY_REPLACEMENTS, regex=False)
  112. )
  113. temp_df['export'] = pd.to_numeric(temp_df['export'].replace('--', 0), errors='coerce')
  114. temp_df = temp_df.drop_duplicates(subset=['commodity'], keep='first')
  115. export_df = pd.concat([export_df, temp_df])
  116. if '进口' in file_path.name:
  117. df = pd.read_excel(file_path, header=None).iloc[5:]
  118. temp_df = df[[name_index, value_index]].rename(columns={name_index: 'commodity', value_index: 'import'})
  119. temp_df['commodity'] = (
  120. temp_df['commodity']
  121. .astype(str)
  122. .apply(lambda x: clean_commodity_name(x, preserve_keywords=PRESERVE_PARENTHESES_KEYWORDS))
  123. .replace(CUSTOM_COMMODITY_REPLACEMENTS, regex=False)
  124. )
  125. temp_df['import'] = pd.to_numeric(temp_df['import'].replace('--', 0), errors='coerce')
  126. temp_df = temp_df.drop_duplicates(subset=['commodity'], keep='first')
  127. import_df = pd.concat([import_df, temp_df])
  128. return export_df, import_df
  129. def hierarchical_traversal(root_path):
  130. """分层遍历:省份->年份->月目录"""
  131. root = Path(root_path)
  132. # 获取所有年份目录
  133. year_dirs = [
  134. item for item in root.iterdir()
  135. if item.is_dir() and base_country_code.YEAR_PATTERN.match(item.name)
  136. ]
  137. # 按年倒序
  138. for year_dir in sorted(year_dirs, key=lambda x: x.name, reverse=True):
  139. log.info(f"\n年份:{year_dir.name} | 省份:hebei")
  140. # 提取月份目录
  141. month_dirs = []
  142. for item in year_dir.iterdir():
  143. if item.is_dir() and base_country_code.MONTH_PATTERN.match(item.name):
  144. month_dirs.append({
  145. "path": item,
  146. "month": int(item.name)
  147. })
  148. # 按月倒序输出
  149. if month_dirs:
  150. for md in sorted(month_dirs, key=lambda x: x["month"], reverse=True):
  151. log.info(f" 月份:{md['month']:02d} | 路径:{md['path']}")
  152. process_folder(md['path'])
  153. if __name__ == '__main__':
  154. hierarchical_traversal(base_country_code.download_dir)
  155. # root = Path(base_country_code.download_dir)/'2023'/'02'
  156. # process_folder(root)
  157. log.info(f"河北石家庄海关出入口商品所有文件处理完成!")