Commit 89b4ef95 by 江名洋

feat: 新增文件名规范化工具,优化上传逻辑并修复表格识别兼容问题

- 修复tests/image_to_excel.py中的PPStructureV3版本返回格式兼容问题,适配新版API返回结果
- 前端harmony.html和analysis.html新增日期范围参数传递逻辑,上传时携带起止日期用于生成规范文件名
- 后端app/api/endpoints.py新增_build_dated_filename函数,实现带日期范围的文件命名规则,更新analysis_upload和harmony_upload接口支持接收日期参数
- 新增create_sample_files.py、多个文件名规范化工具脚本,用于批量规范化temp_uploads目录下的Excel文件格式
- 清理无用的db_check.txt、check_template.txt临时文件,更新_paddle_log.txt内容
- 新增大量临时Excel测试文件到temp_uploads目录
1 parent 59d72f67
Showing 108 changed files with 906 additions and 16 deletions
No preview for this file type
......@@ -18,6 +18,13 @@ from app.services.strategy_service import StrategyService, get_task_state
from app.services.upload_service import (
import_store_guarantee, import_oem_delivery, get_upload_history,
)
from app.services.file_naming import (
build_filename,
build_store_filename,
build_factory_filename,
build_analysis_output_filename,
ensure_unique_filename
)
from app.core.scheduler import SchedulerManager
import os
import shutil
......@@ -32,7 +39,7 @@ os.makedirs(UPLOAD_BASE, exist_ok=True)
def _date_path(filename: str, category: str = "") -> str:
"""生成按日期分级的文件路径: temp_uploads/[category/]YYYYMMDD/filename"""
"""生成按日期分级的文件路径: temp_uploads/YYYYMMDD/filename"""
today = datetime.now().strftime("%Y%m%d")
target_dir = os.path.join(UPLOAD_BASE, category, today) if category else os.path.join(UPLOAD_BASE, today)
os.makedirs(target_dir, exist_ok=True)
......@@ -350,27 +357,68 @@ _analysis_ecology_factory_file = None # 缓存生态主机厂文件路径
_analysis_nature_factory_file = None # 缓存自然月主机厂文件路径
def _build_dated_filename(original_name: str, prefix: str, start_date: str = None, end_date: str = None) -> str:
"""构建带日期范围的文件名: 使用新的命名规范
支持的 prefix:
- analysis_store: 问界门店数据
- analysis_ecology: 问界主机厂数据(生态月)
- analysis_nature: 问界主机厂数据(自然月)
- harmony_store: 鸿蒙门店数据
- harmony_factory: 鸿蒙主机厂数据
"""
# 使用统一的命名规范
if "store" in prefix and "harmony" not in prefix:
return build_store_filename("问界", start_date, end_date)
elif "ecology" in prefix:
return build_factory_filename("问界", "生态月", start_date, end_date)
elif "nature" in prefix:
return build_factory_filename("问界", "自然月", start_date, end_date)
elif "harmony_store" in prefix:
return build_store_filename("鸿蒙", start_date, end_date)
elif "harmony_factory" in prefix:
return build_factory_filename("鸿蒙", "", start_date, end_date)
# 回退到旧的命名方式
stem, ext = os.path.splitext(original_name)
parts = [prefix, stem]
if start_date and end_date:
s = start_date[5:].replace("-", "") if len(start_date) >= 10 else start_date
e = end_date[5:].replace("-", "") if len(end_date) >= 10 else end_date
parts.append(f"{s}~{e}")
elif end_date:
e = end_date[5:].replace("-", "") if len(end_date) >= 10 else end_date
parts.append(e)
return "_".join(parts) + ext
@router.post("/analysis/upload")
async def analysis_upload(
store_file: Optional[UploadFile] = File(None),
ecology_factory_file: Optional[UploadFile] = File(None),
nature_factory_file: Optional[UploadFile] = File(None),
ecology_start_date: str = Form(None),
ecology_end_date: str = Form(None),
nature_start_date: str = Form(None),
nature_end_date: str = Form(None),
):
"""上传门店数据、生态主机厂数据(26日周期)、自然月主机厂数据(1日周期)"""
result = {"status": "success", "messages": []}
if store_file and store_file.filename:
file_path = _date_path(f"analysis_store_{store_file.filename}", category="analysis")
fname = _build_dated_filename(store_file.filename, "analysis_store")
file_path = _date_path(fname, category="analysis")
with open(file_path, "wb") as f:
shutil.copyfileobj(store_file.file, f)
global _analysis_store_file
_analysis_store_file = file_path
result["messages"].append(f"门店列表已上传: {store_file.filename}")
def _save_factory(upload_file, prefix, global_var_name):
def _save_factory(upload_file, prefix, global_var_name, start_date=None, end_date=None):
if not upload_file or not upload_file.filename:
return None
file_path = _date_path(f"analysis_{prefix}_{upload_file.filename}", category="analysis")
fname = _build_dated_filename(upload_file.filename, f"analysis_{prefix}", start_date, end_date)
file_path = _date_path(fname, category="analysis")
with open(file_path, "wb") as f:
shutil.copyfileobj(upload_file.file, f)
try:
......@@ -384,14 +432,14 @@ async def analysis_upload(
except Exception as e:
return {"path": file_path, "error": str(e)}
ecology_info = _save_factory(ecology_factory_file, "ecology", "_analysis_ecology_factory_file")
ecology_info = _save_factory(ecology_factory_file, "ecology", "_analysis_ecology_factory_file", ecology_start_date, ecology_end_date)
if ecology_info:
global _analysis_ecology_factory_file
_analysis_ecology_factory_file = ecology_info.get("path") if not ecology_info.get("error") else None
result["ecology_factory_info"] = ecology_info
result["messages"].append(f"生态主机厂数据已上传: {ecology_factory_file.filename}")
nature_info = _save_factory(nature_factory_file, "nature", "_analysis_nature_factory_file")
nature_info = _save_factory(nature_factory_file, "nature", "_analysis_nature_factory_file", nature_start_date, nature_end_date)
if nature_info:
global _analysis_nature_factory_file
_analysis_nature_factory_file = nature_info.get("path") if not nature_info.get("error") else None
......@@ -697,20 +745,24 @@ _harmony_factory_file = None
async def harmony_upload(
store_file: Optional[UploadFile] = File(None),
factory_file: Optional[UploadFile] = File(None),
start_date: str = Form(None),
end_date: str = Form(None),
):
"""上传鸿蒙门店兜底配置、主机厂数据(产值表数据从数据库自动查询)"""
global _harmony_store_file, _harmony_factory_file
result = {"status": "success", "messages": []}
if store_file and store_file.filename:
file_path = _date_path(f"harmony_store_{store_file.filename}", category="harmony")
fname = _build_dated_filename(store_file.filename, "harmony_store")
file_path = _date_path(fname, category="harmony")
with open(file_path, "wb") as f:
shutil.copyfileobj(store_file.file, f)
_harmony_store_file = file_path
result["messages"].append(f"门店兜底配置已上传: {store_file.filename}")
if factory_file and factory_file.filename:
file_path = _date_path(f"harmony_factory_{factory_file.filename}", category="harmony")
fname = _build_dated_filename(factory_file.filename, "harmony_factory", start_date, end_date)
file_path = _date_path(fname, category="harmony")
with open(file_path, "wb") as f:
shutil.copyfileobj(factory_file.file, f)
_harmony_factory_file = file_path
......
......@@ -14,6 +14,7 @@ from datetime import date, timedelta
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
from app.services.file_naming import build_analysis_output_filename, ensure_unique_filename
logger = logging.getLogger("app.analysis_service")
......@@ -780,14 +781,14 @@ class AnalysisService:
output_dir = os.path.join("temp_uploads", "reports", date.today().strftime("%Y%m%d"))
os.makedirs(output_dir, exist_ok=True)
import time
ts = int(time.time()) # Unix 时间戳
# MMDD 格式 (从 YYYY-MM-DD 提取)
eco_s = ecology_start[5:].replace("-", "") if ecology_start and len(ecology_start) >= 10 else ""
eco_e = ecology_end[5:].replace("-", "") if ecology_end and len(ecology_end) >= 10 else ""
nat_s = nature_start[5:].replace("-", "") if nature_start and len(nature_start) >= 10 else ""
nat_e = nature_end[5:].replace("-", "") if nature_end and len(nature_end) >= 10 else ""
output_path = os.path.join(output_dir, f"问界分析_生态({eco_s}-{eco_e})_自然({nat_s}-{nat_e})_{ts}.xlsx")
# 确定使用哪个日期范围(优先生态月,其次自然月)
start_date = ecology_start if (ecology_start and has_ecology) else nature_start
end_date = ecology_end if (ecology_end and has_ecology) else nature_end
# 使用新的命名规范构建文件名
output_filename = build_analysis_output_filename("问界", start_date, end_date)
output_filename = ensure_unique_filename(output_dir, output_filename)
output_path = os.path.join(output_dir, output_filename)
shutil.copy2(TEMPLATE_FILE, output_path)
wb = load_workbook(output_path)
......
# -*- coding: utf-8 -*-
"""
文件名: app/services/file_naming.py
职责: 统一的文件命名规范工具
命名格式: 品牌-业务类型-数据标签-数据时间范围.xlsx
示例:
- 问界-门店数据-0601~0625.xlsx
- 鸿蒙-主机厂数据-自然月-0601~0625.xlsx
- 鸿蒙-主机厂数据-生态月-0625~0705.xlsx
- 鸿蒙分析-输出-0625~0705.xlsx
"""
import os
import re
from datetime import datetime
def normalize_date_range(start_date: str, end_date: str) -> str:
"""
将日期范围规范化为 MMDD~MMDD 格式
Args:
start_date: 开始日期,支持 YYYY-MM-DD 或 MM-DD 格式
end_date: 结束日期,支持 YYYY-MM-DD 或 MM-DD 格式
Returns:
规范化的日期范围字符串,例如 "0601~0625"
"""
def extract_mmdd(date_str: str) -> str:
if not date_str:
return ""
# 匹配 MM-DD 或 MM/DD 或 MM.DD 格式
match = re.search(r'(\d{1,2})[-.\/](\d{1,2})', date_str)
if match:
month, day = match.groups()
return f"{month.zfill(2)}{day.zfill(2)}"
# 匹配 YYYY-MM-DD 格式
match = re.search(r'(\d{4})[-.\/](\d{1,2})[-.\/](\d{1,2})', date_str)
if match:
_, month, day = match.groups()
return f"{month.zfill(2)}{day.zfill(2)}"
# 已经是 MMDD 格式
if re.match(r'^\d{4}$', date_str):
return date_str
return ""
start_mmdd = extract_mmdd(start_date)
end_mmdd = extract_mmdd(end_date)
if start_mmdd and end_mmdd:
return f"{start_mmdd}~{end_mmdd}"
elif start_mmdd:
return start_mmdd
elif end_mmdd:
return end_mmdd
return ""
def build_filename(
brand: str = "",
business_type: str = "",
data_label: str = "",
date_range: str = "",
extension: str = ".xlsx"
) -> str:
"""
根据命名规范构建文件名
命名格式: 品牌-业务类型-数据标签-数据时间范围.xlsx
Args:
brand: 品牌(问界/鸿蒙)
business_type: 业务类型(门店数据/主机厂数据/分析/输出等)
data_label: 数据标签(自然月/生态月等,可选)
date_range: 时间范围(MMDD~MMDD 格式,可选)
extension: 文件扩展名(默认 .xlsx)
Returns:
规范化的文件名
"""
parts = []
# 品牌
if brand:
if "问界" in brand or "wenjie" in brand.lower():
parts.append("问界")
elif "鸿蒙" in brand or "harmony" in brand.lower():
parts.append("鸿蒙")
else:
parts.append(brand)
# 业务类型
if business_type:
if "门店" in business_type or "store" in business_type.lower():
parts.append("门店数据")
elif "主机厂" in business_type or "oem" in business_type.lower() or "factory" in business_type.lower():
parts.append("主机厂数据")
elif "分析" in business_type or "analysis" in business_type.lower():
parts.append("分析")
elif "输出" in business_type or "output" in business_type.lower():
parts.append("输出")
else:
parts.append(business_type)
# 数据标签
if data_label:
if "自然" in data_label or "nature" in data_label.lower():
parts.append("自然月")
elif "生态" in data_label or "ecology" in data_label.lower():
parts.append("生态月")
else:
parts.append(data_label)
# 时间范围
if date_range:
parts.append(date_range)
if not parts:
return f"unnamed{extension}"
return "-".join(parts) + extension
def build_store_filename(
brand: str,
start_date: str = "",
end_date: str = ""
) -> str:
"""
构建门店数据文件的规范化文件名
Args:
brand: 品牌(问界/鸿蒙)
start_date: 开始日期
end_date: 结束日期
Returns:
规范化的文件名,例如 "问界-门店数据-0601~0625.xlsx"
"""
date_range = normalize_date_range(start_date, end_date)
return build_filename(
brand=brand,
business_type="门店数据",
date_range=date_range
)
def build_factory_filename(
brand: str,
period_type: str = "",
start_date: str = "",
end_date: str = ""
) -> str:
"""
构建主机厂数据文件的规范化文件名
Args:
brand: 品牌(问界/鸿蒙)
period_type: 周期类型(自然月/生态月)
start_date: 开始日期
end_date: 结束日期
Returns:
规范化的文件名,例如 "鸿蒙-主机厂数据-自然月-0601~0625.xlsx"
"""
date_range = normalize_date_range(start_date, end_date)
return build_filename(
brand=brand,
business_type="主机厂数据",
data_label=period_type,
date_range=date_range
)
def build_analysis_output_filename(
brand: str,
start_date: str = "",
end_date: str = ""
) -> str:
"""
构建分析输出文件的规范化文件名
Args:
brand: 品牌(问界/鸿蒙)
start_date: 开始日期
end_date: 结束日期
Returns:
规范化的文件名,例如 "鸿蒙分析-输出-0625~0705.xlsx"
"""
date_range = normalize_date_range(start_date, end_date)
if brand and "问界" in brand:
return build_filename(
brand="问界",
business_type="分析",
data_label="输出",
date_range=date_range
)
else:
return build_filename(
brand="鸿蒙",
business_type="分析",
data_label="输出",
date_range=date_range
)
def get_timestamp() -> str:
"""获取时间戳,用于避免文件名冲突"""
return datetime.now().strftime("%H%M%S")
def ensure_unique_filename(directory: str, filename: str) -> str:
"""
确保文件名唯一,如果有冲突则添加序号
Args:
directory: 文件所在目录
filename: 原始文件名
Returns:
唯一的文件名
"""
base, ext = os.path.splitext(filename)
counter = 1
while os.path.exists(os.path.join(directory, filename)):
filename = f"{base}_{counter}{ext}"
counter += 1
return filename
......@@ -530,6 +530,15 @@
if (hasStoreFile) uploadForm.append('store_file', storeInput.files[0]);
if (hasEcoFile) uploadForm.append('ecology_factory_file', ecoInput.files[0]);
if (hasNatFile) uploadForm.append('nature_factory_file', natInput.files[0]);
// 传日期范围用于文件命名
const eS2 = document.getElementById('ecology-start-date').value;
const eE2 = document.getElementById('ecology-end-date').value;
const nS2 = document.getElementById('nature-start-date').value;
const nE2 = document.getElementById('nature-end-date').value;
if (eS2) uploadForm.append('ecology_start_date', eS2);
if (eE2) uploadForm.append('ecology_end_date', eE2);
if (nS2) uploadForm.append('nature_start_date', nS2);
if (nE2) uploadForm.append('nature_end_date', nE2);
const anyFile = hasStoreFile || hasEcoFile || hasNatFile;
if (anyFile) {
......
......@@ -345,6 +345,11 @@
const uploadForm = new FormData();
if (hasStoreFile) uploadForm.append('store_file', storeInput.files[0]);
if (hasFactoryFile) uploadForm.append('factory_file', factoryInput.files[0]);
// 传日期范围用于文件命名
const sd2 = document.getElementById('hm-start-date').value;
const ed2 = document.getElementById('hm-end-date').value;
if (sd2) uploadForm.append('start_date', sd2);
if (ed2) uploadForm.append('end_date', ed2);
const anyFile = hasStoreFile || hasFactoryFile;
if (anyFile) {
......
No preview for this file type
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文件名: create_sample_files.py
职责: 创建符合用户要求格式的示例文件
格式:
- 问界-门店数据-MMDD~MMDD.xlsx
- 鸿蒙-主机厂数据-自然月-MMDD~MMDD.xlsx
- 鸿蒙-主机厂数据-生态月-MMDD~MMDD.xlsx
"""
import os
from pathlib import Path
import openpyxl
def create_excel_file(file_path):
"""创建一个简单的 Excel 文件"""
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Sheet1"
ws['A1'] = "示例数据"
ws['A2'] = "这是一个示例文件"
wb.save(file_path)
def main():
temp_uploads_dir = Path(__file__).parent / 'temp_uploads'
# 确保目录存在
temp_uploads_dir.mkdir(exist_ok=True)
# 创建示例文件
sample_files = [
"问界-门店数据-0601~0625.xlsx",
"鸿蒙-主机厂数据-自然月-0601~0625.xlsx",
"鸿蒙-主机厂数据-生态月-0625~0705.xlsx",
]
print("创建示例文件:")
for filename in sample_files:
file_path = temp_uploads_dir / filename
create_excel_file(file_path)
print(f" {filename}")
print("\n完成! 已在 temp_uploads 目录下创建示例文件。")
if __name__ == '__main__':
main()
\ No newline at end of file
No preview for this file type
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文件名: filename_normalizer.py
职责: 文件名规范化工具
支持的目标格式:
- 问界门店数据: 问界-门店数据-MMDD~MMDD.xlsx
- 鸿蒙主机厂数据自然月: 鸿蒙-主机厂数据-自然月-MMDD~MMDD.xlsx
- 鸿蒙主机厂数据生态月: 鸿蒙-主机厂数据-生态月-MMDD~MMDD.xlsx
使用方法:
1. 分析现有文件: python filename_normalizer.py analyze
2. 预览重命名结果: python filename_normalizer.py preview
3. 执行重命名: python filename_normalizer.py run
"""
import os
import re
import shutil
import sys
from pathlib import Path
class FilenameNormalizer:
def __init__(self, target_dir):
self.target_dir = Path(target_dir)
self.rename_map = {}
def analyze_file(self, filename):
"""分析单个文件,提取信息"""
name, ext = os.path.splitext(filename)
info = {
'original': filename,
'brand': None,
'data_type': None,
'period_type': None,
'date_range': None,
'ext': ext
}
# 识别品牌
if '问界' in name:
info['brand'] = '问界'
elif '鸿蒙' in name:
info['brand'] = '鸿蒙'
# 识别数据类型
if '门店' in name:
info['data_type'] = '门店数据'
elif '主机厂' in name or 'oem' in name.lower() or 'factory' in name.lower():
info['data_type'] = '主机厂数据'
# 识别周期类型
if '生态' in name:
info['period_type'] = '生态月'
elif '自然' in name:
info['period_type'] = '自然月'
# 提取日期范围
# 模式: 5.26-6.25 或 0601~0625
date_patterns = [
r'(\d{1,2})[.\/-](\d{1,2})\s*[~至-]\s*(\d{1,2})[.\/-](\d{1,2})',
r'(\d{4})\s*[~至-]\s*(\d{4})'
]
for pattern in date_patterns:
match = re.search(pattern, name)
if match:
groups = match.groups()
if len(groups) == 4:
m1, d1, m2, d2 = groups
info['date_range'] = f"{m1.zfill(2)}{d1.zfill(2)}~{m2.zfill(2)}{d2.zfill(2)}"
elif len(groups) == 2:
info['date_range'] = f"{groups[0]}~{groups[1]}"
break
return info
def build_normalized_name(self, info):
"""根据信息构建规范化文件名"""
parts = []
if info['brand']:
parts.append(info['brand'])
if info['data_type']:
parts.append(info['data_type'])
if info['period_type']:
parts.append(info['period_type'])
if info['date_range']:
parts.append(info['date_range'])
if parts:
return '-'.join(parts) + info['ext']
return None
def analyze(self):
"""分析目录下所有 Excel 文件"""
print(f"分析目录: {self.target_dir}")
print("-" * 80)
files = list(self.target_dir.rglob('*.xlsx'))
for file_path in files:
if file_path.is_file():
info = self.analyze_file(file_path.name)
normalized = self.build_normalized_name(info)
self.rename_map[file_path] = {
'info': info,
'normalized': normalized
}
status = "✓ 可规范化" if normalized else "✗ 无法识别"
print(f"{status} {file_path.name:60}")
if normalized:
print(f" -> {normalized}")
print("-" * 80)
print(f"总计: {len(files)} 个文件")
print(f"可规范化: {sum(1 for v in self.rename_map.values() if v['normalized'])} 个")
def preview(self):
"""预览重命名结果"""
if not self.rename_map:
self.analyze()
print("\n预览重命名结果:")
print("=" * 80)
for file_path, data in self.rename_map.items():
if data['normalized']:
print(f"{file_path.name:60} -> {data['normalized']}")
print("=" * 80)
def run(self, dry_run=True):
"""执行重命名"""
if not self.rename_map:
self.analyze()
if dry_run:
print("\n[模拟运行] 不会实际修改文件")
else:
print("\n[实际运行] 开始重命名...")
print("-" * 80)
count = 0
for file_path, data in self.rename_map.items():
normalized = data['normalized']
if normalized:
new_path = file_path.parent / normalized
# 处理文件名冲突
counter = 1
base_name, ext = os.path.splitext(normalized)
while new_path.exists() and new_path != file_path:
new_path = file_path.parent / f"{base_name}_{counter}{ext}"
counter += 1
if new_path != file_path:
print(f"{file_path.name:60} -> {new_path.name}")
if not dry_run:
shutil.move(str(file_path), str(new_path))
count += 1
print("-" * 80)
if dry_run:
print(f"[模拟完成] 预计重命名 {count} 个文件")
else:
print(f"[完成] 重命名了 {count} 个文件")
def main():
target_dir = Path(__file__).parent / 'temp_uploads'
normalizer = FilenameNormalizer(target_dir)
if len(sys.argv) > 1:
command = sys.argv[1].lower()
if command == 'analyze':
normalizer.analyze()
elif command == 'preview':
normalizer.preview()
elif command == 'run':
normalizer.run(dry_run=False)
else:
print("未知命令。使用方法:")
print(" python filename_normalizer.py analyze - 分析文件")
print(" python filename_normalizer.py preview - 预览重命名")
print(" python filename_normalizer.py run - 执行重命名")
else:
# 默认分析
normalizer.analyze()
if __name__ == '__main__':
main()
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文件名: normalize_filenames.py
职责: 规范化 temp_uploads 目录下的 Excel 文件名
"""
import os
import re
import shutil
from pathlib import Path
def normalize_filename(filename):
"""
规范化文件名
规则:
- 问界门店数据: 问界-门店数据-MMDD~MMDD.xlsx
- 鸿蒙主机厂数据自然月: 鸿蒙-主机厂数据-自然月-MMDD~MMDD.xlsx
- 鸿蒙主机厂数据生态月: 鸿蒙-主机厂数据-生态月-MMDD~MMDD.xlsx
"""
# 去掉扩展名
name = filename
ext = ''
if '.' in filename:
name, ext = filename.rsplit('.', 1)
ext = '.' + ext.lower()
# 规范化日期格式:将 5.26、6.1、6.25 等转换为 MMDD
def normalize_date(match):
date_str = match.group(0)
# 匹配 5.26、6.1、6.25 等格式
m = re.match(r'(\d{1,2})[.\/-](\d{1,2})', date_str)
if m:
month = m.group(1).zfill(2)
day = m.group(2).zfill(2)
return f'{month}{day}'
return date_str
# 替换日期格式
name = re.sub(r'\d{1,2}[.\/-]\d{1,2}', normalize_date, name)
# 替换 ( ) 为 -
name = name.replace('(', '-').replace(')', '-')
# 替换多个连续的 - 为单个 -
name = re.sub(r'-+', '-', name)
# 替换 _ 为 -
name = name.replace('_', '-')
# 规范化品牌名称
name = re.sub(r'wenjie|问界', '问界', name, flags=re.IGNORECASE)
name = re.sub(r'harmony|鸿蒙', '鸿蒙', name, flags=re.IGNORECASE)
# 规范化数据类型
name = re.sub(r'门店|store', '门店数据', name, flags=re.IGNORECASE)
name = re.sub(r'oem|主机厂', '主机厂数据', name, flags=re.IGNORECASE)
# 规范化周期类型
name = re.sub(r'nature|自然', '自然月', name, flags=re.IGNORECASE)
name = re.sub(r'ecology|生态', '生态月', name, flags=re.IGNORECASE)
# 规范化日期范围分隔符
name = re.sub(r'~+', '~', name)
name = re.sub(r'-(\d{4})~', '~\g<1>', name) # 修复类似 -0601~0625 的格式
# 去掉开头和结尾的 -
name = name.strip('-')
return name + ext
def main():
temp_uploads_dir = Path(__file__).parent / 'temp_uploads'
if not temp_uploads_dir.exists():
print(f'目录不存在: {temp_uploads_dir}')
return
# 统计信息
renamed_count = 0
skipped_count = 0
# 遍历所有 Excel 文件
for file_path in temp_uploads_dir.rglob('*.xlsx'):
if file_path.is_file():
old_name = file_path.name
new_name = normalize_filename(old_name)
if old_name != new_name:
new_path = file_path.parent / new_name
# 如果目标文件已存在,添加序号
counter = 1
while new_path.exists():
name_part, ext_part = os.path.splitext(new_name)
new_path = file_path.parent / f'{name_part}_{counter}{ext_part}'
counter += 1
print(f'重命名: {old_name} -> {new_path.name}')
shutil.move(str(file_path), str(new_path))
renamed_count += 1
else:
skipped_count += 1
print(f'\n完成: 重命名 {renamed_count} 个文件,跳过 {skipped_count} 个文件')
if __name__ == '__main__':
main()
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文件名: normalize_filenames_final.py
职责: 规范化 temp_uploads 目录下的 Excel 文件名
目标格式:
- 问界门店数据: 问界-门店数据-MMDD~MMDD.xlsx
- 鸿蒙主机厂数据自然月: 鸿蒙-主机厂数据-自然月-MMDD~MMDD.xlsx
- 鸿蒙主机厂数据生态月: 鸿蒙-主机厂数据-生态月-MMDD~MMDD.xlsx
"""
import os
import re
import shutil
from pathlib import Path
def extract_info(filename):
"""从文件名中提取关键信息"""
name, ext = os.path.splitext(filename)
brand = None
data_type = None
period_type = None
date_range = None
# 识别品牌
if '问界' in name:
brand = '问界'
elif '鸿蒙' in name:
brand = '鸿蒙'
# 识别数据类型
if '门店' in name:
data_type = '门店数据'
elif '主机厂' in name or 'oem' in name.lower() or 'factory' in name.lower():
data_type = '主机厂数据'
# 识别周期类型
if '生态' in name:
period_type = '生态月'
elif '自然' in name:
period_type = '自然月'
# 提取和规范化日期范围
# 模式1: 5.26-6.25 或 5.26~6.25
date_match = re.search(r'(\d{1,2})[.\/-](\d{1,2})\s*[~至-]\s*(\d{1,2})[.\/-](\d{1,2})', name)
if date_match:
m1, d1, m2, d2 = date_match.groups()
date_range = f"{m1.zfill(2)}{d1.zfill(2)}~{m2.zfill(2)}{d2.zfill(2)}"
else:
# 模式2: 0601~0625
date_match = re.search(r'(\d{4})\s*[~至-]\s*(\d{4})', name)
if date_match:
d1, d2 = date_match.groups()
date_range = f"{d1}~{d2}"
return {
'brand': brand,
'data_type': data_type,
'period_type': period_type,
'date_range': date_range,
'ext': ext
}
def build_filename(info):
"""根据信息构建规范化文件名"""
parts = []
if info['brand']:
parts.append(info['brand'])
if info['data_type']:
parts.append(info['data_type'])
if info['period_type']:
parts.append(info['period_type'])
if info['date_range']:
parts.append(info['date_range'])
if parts:
return '-'.join(parts) + info['ext']
else:
# 无法识别的文件保持原样
return None
def main():
temp_uploads_dir = Path(__file__).parent / 'temp_uploads'
if not temp_uploads_dir.exists():
print(f'目录不存在: {temp_uploads_dir}')
return
print('=== temp_uploads 文件名规范化 ===')
print('目标格式:')
print(' - 问界门店数据: 问界-门店数据-MMDD~MMDD.xlsx')
print(' - 鸿蒙主机厂数据自然月: 鸿蒙-主机厂数据-自然月-MMDD~MMDD.xlsx')
print(' - 鸿蒙主机厂数据生态月: 鸿蒙-主机厂数据-生态月-MMDD~MMDD.xlsx')
print()
renamed_count = 0
skipped_count = 0
# 遍历所有 Excel 文件
for file_path in temp_uploads_dir.rglob('*.xlsx'):
if file_path.is_file():
old_name = file_path.name
info = extract_info(old_name)
new_name = build_filename(info)
if new_name and new_name != old_name:
new_path = file_path.parent / new_name
# 如果目标文件已存在,添加序号
counter = 1
base_name, ext = os.path.splitext(new_name)
while new_path.exists():
new_path = file_path.parent / f"{base_name}_{counter}{ext}"
counter += 1
print(f'{old_name:60} -> {new_path.name}')
shutil.move(str(file_path), str(new_path))
renamed_count += 1
else:
skipped_count += 1
print()
print(f'完成: 重命名 {renamed_count} 个文件,跳过 {skipped_count} 个文件')
if __name__ == '__main__':
main()
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文件名: normalize_filenames_v2.py
职责: 规范化 temp_uploads 目录下的 Excel 文件名
目标格式:
- 问界门店数据: 问界-门店数据-MMDD~MMDD.xlsx
- 鸿蒙主机厂数据自然月: 鸿蒙-主机厂数据-自然月-MMDD~MMDD.xlsx
- 鸿蒙主机厂数据生态月: 鸿蒙-主机厂数据-生态月-MMDD~MMDD.xlsx
"""
import os
import re
import shutil
from pathlib import Path
def normalize_filename(filename):
"""规范化文件名"""
name, ext = os.path.splitext(filename)
# 提取关键信息
brand = None
data_type = None
period_type = None
date_range = None
# 识别品牌
if '问界' in name or 'wenjie' in name.lower():
brand = '问界'
elif '鸿蒙' in name or 'harmony' in name.lower():
brand = '鸿蒙'
# 识别数据类型
if '门店' in name or 'store' in name.lower():
data_type = '门店数据'
elif '主机厂' in name or 'oem' in name.lower() or 'factory' in name.lower():
data_type = '主机厂数据'
# 识别周期类型
if '生态' in name or 'ecology' in name.lower():
period_type = '生态月'
elif '自然' in name or 'nature' in name.lower():
period_type = '自然月'
# 提取和规范化日期范围
# 查找日期模式: MM.DD-MM.DD, MMDD~MMDD, 等
date_patterns = [
r'(\d{1,2})[.\/-](\d{1,2})\s*[~至-]\s*(\d{1,2})[.\/-](\d{1,2})', # 5.26-6.25
r'(\d{4})\s*[~至-]\s*(\d{4})', # 0601~0625
r'(\d{2})(\d{2})\s*[~至-]\s*(\d{2})(\d{2})', # 06010625 (需要检查是否是日期)
]
for pattern in date_patterns:
match = re.search(pattern, name)
if match:
groups = match.groups()
if len(groups) == 4:
# 格式: MM.DD~MM.DD
m1, d1, m2, d2 = groups
date_range = f"{m1.zfill(2)}{d1.zfill(2)}~{m2.zfill(2)}{d2.zfill(2)}"
elif len(groups) == 2:
# 格式: MMDD~MMDD
d1, d2 = groups
if len(d1) == 4 and len(d2) == 4:
date_range = f"{d1}~{d2}"
break
# 构建新文件名
parts = []
if brand:
parts.append(brand)
if data_type:
parts.append(data_type)
if period_type:
parts.append(period_type)
if date_range:
parts.append(date_range)
if parts:
new_name = '-'.join(parts) + ext
else:
# 如果无法识别,保持原样但清理一下
new_name = filename
return new_name
def main():
temp_uploads_dir = Path(__file__).parent / 'temp_uploads'
if not temp_uploads_dir.exists():
print(f'目录不存在: {temp_uploads_dir}')
return
# 先把上次重命名的文件还原(通过git或者手动),这里我们演示正确的规范化
print('=== 文件名规范化示例 ===')
print('目标格式:')
print(' - 问界门店数据: 问界-门店数据-MMDD~MMDD.xlsx')
print(' - 鸿蒙主机厂数据自然月: 鸿蒙-主机厂数据-自然月-MMDD~MMDD.xlsx')
print(' - 鸿蒙主机厂数据生态月: 鸿蒙-主机厂数据-生态月-MMDD~MMDD.xlsx')
print()
# 遍历并显示建议的重命名
examples = [
'问界-门店数据-0601~0625.xlsx',
'鸿蒙-主机厂数据-自然月-0601~0625.xlsx',
'鸿蒙-主机厂数据-生态月-0625~0705.xlsx',
]
print('示例文件名:')
for ex in examples:
print(f' {ex}')
print()
print('注意: 由于之前的脚本已经重命名了文件,建议手动恢复或使用git恢复后,再使用精确的规则。')
print('你想要我创建一个更精确的版本吗?')
if __name__ == '__main__':
main()
\ No newline at end of file
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!