normalize_all_files.py
7.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文件名: normalize_all_files.py
职责: 整理 temp_uploads 目录下的所有文件,统一按照新的命名规范进行重命名
命名规范:
- 问界门店数据: 问界-门店数据-MMDD~MMDD.xlsx
- 鸿蒙门店数据: 鸿蒙-门店数据-MMDD~MMDD.xlsx
- 问界主机厂数据(自然月): 问界-主机厂数据-自然月-MMDD~MMDD.xlsx
- 问界主机厂数据(生态月): 问界-主机厂数据-生态月-MMDD~MMDD.xlsx
- 鸿蒙主机厂数据: 鸿蒙-主机厂数据-MMDD~MMDD.xlsx
- 问界分析输出: 问界-分析-输出-MMDD~MMDD.xlsx
- 鸿蒙分析输出: 鸿蒙-分析-输出-MMDD~MMDD.xlsx
"""
import os
import re
import shutil
import sys
from pathlib import Path
from datetime import datetime
def extract_info_from_filename(filename):
"""从现有文件名中提取关键信息"""
name, ext = os.path.splitext(filename)
if ext.lower() not in ('.xlsx', '.xls'):
return None
info = {
'original': filename,
'brand': None,
'business_type': None,
'period_type': None,
'date_range': None,
'ext': ext
}
# 提取品牌
if '问界' in name or 'wenjie' in name.lower():
info['brand'] = '问界'
elif '鸿蒙' in name or 'harmony' in name.lower():
info['brand'] = '鸿蒙'
# 提取业务类型
if '门店' in name or 'store' in name.lower():
info['business_type'] = '门店数据'
elif '主机厂' in name or 'oem' in name.lower() or 'factory' in name.lower():
info['business_type'] = '主机厂数据'
elif '分析' in name or 'analysis' in name.lower() or 'output' in name.lower() or '输出' in name:
info['business_type'] = '分析'
info['period_type'] = '输出'
# 提取周期类型
if info['business_type'] == '主机厂数据':
if '生态' in name or 'ecology' in name.lower():
info['period_type'] = '生态月'
elif '自然' in name or 'nature' in name.lower():
info['period_type'] = '自然月'
# 提取日期范围
date_patterns = [
# 1. 匹配 2024.06.01-2024.06.25 格式 (最完整,优先)
r'20\d{2}[.\-\/](\d{1,2})[.\-\/](\d{1,2})[~至-]20\d{2}[.\-\/](\d{1,2})[.\-\/](\d{1,2})',
# 2. 匹配 20240601~20240625 格式
r'20\d{2}(\d{4})[~至-]20\d{2}(\d{4})',
# 3. 匹配 MM.DD~MM.DD 或 MM/DD~MM/DD 格式 (确保不是 YY.MM)
r'(?<!\d)([01]?\d)[.\-\/]([0-3]?\d)[~至-]([01]?\d)[.\-\/]([0-3]?\d)(?!\d)',
# 4. 匹配 MMDD~MMDD 格式 (4位数字~4位数字)
r'(?<!\d)([01]\d[0-3]\d)[~至-]([01]\d[0-3]\d)(?!\d)',
]
for pattern in date_patterns:
match = re.search(pattern, name)
if match:
groups = match.groups()
if len(groups) == 2:
# MMDD~MMDD 格式
info['date_range'] = f"{groups[0]}~{groups[1]}"
elif len(groups) == 4:
# MM.DD~MM.DD 格式
m1, d1, m2, d2 = groups
info['date_range'] = f"{m1.zfill(2)}{d1.zfill(2)}~{m2.zfill(2)}{d2.zfill(2)}"
break
# 如果没有提取到日期,尝试从文件名中提取任意 8 位数字作为 MMDD
if not info['date_range']:
# 查找 8 位数字作为 YYYYMMDD
date_match = re.search(r'20\d{2}(\d{4})', name)
if date_match:
mmdd = date_match.group(1)
info['date_range'] = f"{mmdd}~{mmdd}"
else:
# 查找 4 位数字且符合 MMDD 校验
date_match = re.search(r'(?<!\d)([01]\d[0-3]\d)(?!\d)', name)
if date_match:
mmdd = date_match.group(1)
m, d = int(mmdd[:2]), int(mmdd[2:])
if 1 <= m <= 12 and 1 <= d <= 31:
info['date_range'] = mmdd
return info
def build_normalized_filename(info):
"""根据提取的信息构建规范化文件名"""
parts = []
if info['brand']:
parts.append(info['brand'])
if info['business_type']:
parts.append(info['business_type'])
if info['period_type']:
parts.append(info['period_type'])
if info['date_range']:
parts.append(info['date_range'])
if not parts:
return None
return '-'.join(parts) + info['ext']
def normalize_directory(directory, dry_run=True):
"""规范化目录下的所有文件"""
directory = Path(directory)
if not directory.exists():
print(f"目录不存在: {directory}")
return
print(f"{'[模拟] ' if dry_run else ''}开始处理目录: {directory}")
print("=" * 80)
renamed_count = 0
skipped_count = 0
failed_count = 0
conflicts = {}
# 遍历目录
for root, dirs, files in os.walk(directory):
for filename in files:
# 跳过隐藏文件
if filename.startswith('.'):
continue
file_path = Path(root) / filename
# 提取信息
info = extract_info_from_filename(filename)
if not info:
print(f"[跳过] 无法识别文件类型: {filename}")
skipped_count += 1
continue
# 构建新文件名
new_filename = build_normalized_filename(info)
if not new_filename:
print(f"[跳过] 无法构建规范文件名: {filename}")
skipped_count += 1
continue
# 检查是否需要重命名
if new_filename == filename:
print(f"[无需修改] {filename}")
skipped_count += 1
continue
# 处理同名文件冲突
new_path = Path(root) / new_filename
counter = 1
while new_path.exists() and new_path != file_path:
base, ext = os.path.splitext(new_filename)
new_path = Path(root) / f"{base}_{counter}{ext}"
counter += 1
# 执行重命名
print(f"{'[模拟] ' if dry_run else ''}{filename:<60} -> {new_path.name}")
if not dry_run:
try:
shutil.move(str(file_path), str(new_path))
renamed_count += 1
except Exception as e:
print(f"[失败] 重命名 {filename} 失败: {e}")
failed_count += 1
else:
renamed_count += 1
print("=" * 80)
print(f"{'[模拟] ' if dry_run else ''}完成! 重命名: {renamed_count}, 跳过: {skipped_count}, 失败: {failed_count}")
def main():
temp_uploads_dir = str(Path(__file__).parent.parent / 'temp_uploads')
if len(sys.argv) > 1 and sys.argv[1] == "--run":
# 实际执行
confirm = input("确定要执行重命名操作吗?这将修改文件系统。(y/N): ")
if confirm.lower() == 'y':
normalize_directory(temp_uploads_dir, dry_run=False)
else:
print("操作已取消")
else:
# 模拟运行
print("这是模拟运行,不会实际修改文件。")
print("要实际执行,请运行: python normalize_all_files.py --run")
print()
normalize_directory(temp_uploads_dir, dry_run=True)
if __name__ == "__main__":
main()