gov_commodity_anhui_import_export.py 7.7 KB

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