一、背景需求
从孩子通上获取家长的手机号,用全选复制的方法获取的信息很多,很乱
二、Python清洗数据
效果还是一样
还是老样子,我感觉需要上传附件。
复制一份,保留第一个,后面的幼儿数据都删除,复制第一组数据做3个假数据
问题出在我要求读取的是sheet3,不是默认第一张的sheet1
接下去,我要默认删除大三班、大班3班字样
希望把身份和手机号复制到姓名的后面
它把三组信息都做了
用真数据跑一次
''' 把孩子通复制出来的整页号码,Python删除空行,家长手机号码横向排列 deepseek,阿夏 202061029 ''' import openpyxl import os import re from openpyxl.styles import Font, Alignment def transform_excel_perfectly(): # ================= 配置区 ================= path = r'D:\000Python网页html\20261026破译电话号码' input_file = os.path.join(path, '大3班.xlsx') # input_file = os.path.join(path, '大3班假.xlsx') output_file = os.path.join(path, '真实大3班_最终完美合并版.xlsx') # ========================================= if not os.path.exists(input_file): print(f"❌ 找不到文件: {input_file}") return print("正在读取原始数据...") wb = openpyxl.load_workbook(input_file, data_only=True) ws = wb.worksheets[2] # 读取 Sheet3 final_data = [] current_student = None for row in ws.iter_rows(values_only=True): row_values = [str(cell).strip() if cell is not None else "" for cell in row] if not any(row_values): continue row_text = "|".join(row_values) if any(kw in row_text for kw in ['已激活', '未激活', '大班3班', '大三班', '学生称谓']): continue col_a = row_values[0] # 1. 识别学号 match_sid = re.search(r'学号[::]\s*(\d+)', col_a) if match_sid: if current_student: current_student['id'] = match_sid.group(1) continue # 2. 识别姓名(【修改点】:增加了排除 '学生'、'姓名' 等表头词的判断) roles = ['妈妈', '爸爸', '奶奶', '爷爷', '外公', '外婆', '父亲', '母亲'] invalid_names = ['学生', '姓名', '学生姓名', '幼儿', '幼儿姓名'] if 2 <= len(col_a) <= 4 and all('\u4e00' <= char <= '\u9fa5' for char in col_a) \ and col_a not in roles and '修改' not in col_a and col_a not in invalid_names: if current_student: final_data.append([current_student['id'], current_student['name']] + current_student['parents']) current_student = { 'id': '', 'name': col_a, 'parents': [] } continue # 3. 识别家长信息 if current_student and (col_a in roles or re.search(r'1[3-9]\d{9}', row_text)): valid_cells = [val for val in row_values if val != ""] while len(valid_cells) < 3: valid_cells.append("") current_student['parents'].extend(valid_cells[:3]) if current_student: final_data.append([current_student['id'], current_student['name']] + current_student['parents']) print(f"✅ 解析完毕,共提取到 {len(final_data)} 个学生及所有家长信息。正在生成新表...") out_wb = openpyxl.Workbook() out_ws = out_wb.active out_ws.title = "完美合并版" max_parent_len = max([len(row) - 2 for row in final_data]) if final_data else 0 # 构建表头 headers = ["学号", "姓名"] for i in range(1, (max_parent_len // 3) + 1): headers.extend([f"身份{i}", f"号码{i}", f"编号{i}"]) for i in range(len(headers) - 2, max_parent_len): headers.append(f"信息{i+1}") out_ws.append(headers) # 写入数据 for row in final_data: out_ws.append(row) # 样式美化 header_font = Font(bold=True) for col_idx, cell in enumerate(out_ws[1], start=1): cell.font = header_font cell.alignment = Alignment(horizontal="center", vertical="center") max_len = len(str(cell.value)) for r_idx in range(2, out_ws.max_row + 1): val = str(out_ws.cell(row=r_idx, column=col_idx).value or "") if len(val) > max_len: max_len = len(val) out_ws.column_dimensions[openpyxl.utils.get_column_letter(col_idx)].width = max(max_len + 4, 12) try: out_wb.save(output_file) print(f"🎉 完美!已过滤掉'学生'表头,表格生成成功。") print(f"📁 文件已保存至: {output_file}") except Exception as e: print(f"❌ 保存失败: {e}") if __name__ == '__main__': transform_excel_perfectly()很好,正确把网页复制的乱码数字调整为HTML需要的格式![]()
但是孩子通默认有两组登录编号(妈妈和爸爸),如果只有妈妈绑定手机号和登录编号,爸爸没有绑定手机(空),但也有登录编号。就会出现手机号的位置上填写的是登录编号。
、
''' 把孩子通复制出来的整页号码,Python删除空行,家长手机号码横向排列 deepseek,阿夏 202061029 ''' import openpyxl import os import re from openpyxl.styles import Font, Alignment def transform_excel_perfectly(): # ================= 配置区 ================= path = r'D:\000Python网页html\20261026破译电话号码' # input_file = os.path.join(path, '大3班假.xlsx') # output_file = os.path.join(path, '大3班_最终完美合并版.xlsx') input_file = os.path.join(path, '大3班.xlsx') output_file = os.path.join(path, '真实大3班_最终完美合并版.xlsx') # ========================================= if not os.path.exists(input_file): print(f"❌ 找不到文件: {input_file}") return print("正在读取原始数据...") wb = openpyxl.load_workbook(input_file, data_only=True) ws = wb.worksheets[2] # 读取 Sheet3 final_data = [] current_student = None # 【核心修复1】:直接跳过第一行表头,从第二行开始遍历 for row in ws.iter_rows(min_row=2, values_only=True): row_values = [str(cell).strip() if cell is not None else "" for cell in row] if not any(row_values): continue row_text = "|".join(row_values) # 过滤无用行(如已激活等) if any(kw in row_text for kw in ['已激活', '未激活', '大班3班', '大三班']): continue col_a = row_values[0] col_b = row_values[1] if len(row_values) > 1 else "" col_c = row_values[2] if len(row_values) > 2 else "" col_d = row_values[3] if len(row_values) > 3 else "" # 1. 识别姓名(此时已经是第2行以后了,排除了表头干扰) roles = ['妈妈', '爸爸', '奶奶', '爷爷', '外公', '外婆', '父亲', '母亲'] invalid_names = ['学生', '姓名', '学生姓名', '幼儿', '幼儿姓名', '称谓', '操作', '修改学生'] if 2 <= len(col_a) <= 4 and all('\u4e00' <= char <= '\u9fa5' for char in col_a) \ and col_a not in roles and '修改' not in col_a and col_a not in invalid_names: # 遇到新名字时,先把上一个积攒好的学生存进列表 if current_student: final_data.append([current_student['id'], current_student['name']] + current_student['parents']) # 创建新学生,此时学号先留空 current_student = { 'id': '', 'name': col_a, 'parents': [] } continue # 2. 识别学号(【核心修复2】:此时读到的学号,塞给刚刚存下的那个 current_student) match_sid = re.search(r'学号[::]\s*(\d+)', col_a) if match_sid and current_student: current_student['id'] = match_sid.group(1) continue # 3. 识别家长信息 if current_student and col_a in roles: current_student['parents'].extend([col_a, col_b, col_c]) # 把最后一个学生存进去 if current_student: final_data.append([current_student['id'], current_student['name']] + current_student['parents']) print(f"✅ 解析完毕,共提取到 {len(final_data)} 个学生。正在生成新表...") out_wb = openpyxl.Workbook() out_ws = out_wb.active out_ws.title = "完美合并版" max_parent_len = max([len(row) - 2 for row in final_data]) if final_data else 0 # 构建表头 headers = ["学号", "姓名"] for i in range(1, (max_parent_len // 3) + 1): headers.extend([f"身份{i}", f"号码{i}", f"编号{i}"]) for i in range(len(headers) - 2, max_parent_len): headers.append(f"信息{i+1}") out_ws.append(headers) # 写入数据 for row in final_data: out_ws.append(row) # 样式美化 header_font = Font(bold=True) for col_idx, cell in enumerate(out_ws[1], start=1): cell.font = header_font cell.alignment = Alignment(horizontal="center", vertical="center") max_len = len(str(cell.value)) for r_idx in range(2, out_ws.max_row + 1): val = str(out_ws.cell(row=r_idx, column=col_idx).value or "") if len(val) > max_len: max_len = len(val) out_ws.column_dimensions[openpyxl.utils.get_column_letter(col_idx)].width = max(max_len + 4, 12) try: out_wb.save(output_file) print(f"🎉 完美!学号已跟姓名绝对对齐。") print(f"📁 文件已保存至: {output_file}") except Exception as e: print(f"❌ 保存失败: {e}") if __name__ == '__main__': transform_excel_perfectly()三、同样方法再做一个班级
四、合并班级
考虑把所有班级做在一个xlsx内
''' 制作20个班级工作表 deepseek,阿夏 202061029 ''' import openpyxl import os def create_multi_sheet_excel(): # 1. 定义保存路径 folder_path = r'D:\000Python网页html\20261026破译电话号码' file_path = os.path.join(folder_path, '孩子通提取所有班级的手机号码.xlsx') # 检查并创建文件夹(如果123文件夹不存在) if not os.path.exists(folder_path): os.makedirs(folder_path) print(f"✅ 已自动创建文件夹: {folder_path}") # 2. 创建工作簿 wb = openpyxl.Workbook() # 3. 准备工作表名称列表 sheets = [] # 托班 1-3 sheets.extend([f"托{i}" for i in range(1, 4)]) # 小班 1-5 sheets.extend([f"小{i}" for i in range(1, 6)]) # 中班 1-6 sheets.extend([f"中{i}" for i in range(1, 7)]) # 大班 1-5 sheets.extend([f"大{i}" for i in range(1, 6)]) # 4. 创建第一个工作表(因为Workbook默认会有一个Sheet,我们用来建第一个) wb.active.title = sheets[0] # 5. 循环创建剩余的工作表 for sheet_name in sheets[1:]: wb.create_sheet(title=sheet_name) # 6. 保存文件 try: wb.save(file_path) print(f"🎉 成功创建 Excel 文件:{file_path}") print(f"📊 共创建了 {len(sheets)} 个工作表。") print("包含班级:", "、".join(sheets)) except Exception as e: print(f"❌ 保存失败: {e}") print("提示:如果保存失败,请检查 123/111.xlsx 是否正在被 Excel 或 WPS 打开。") if __name__ == '__main__': create_multi_sheet_excel()把园园通数据放进去
暂时放四个班级
出现其他身份,哥哥单独一行
修改后各种可以填写的身份。
把20个班级的手机号都复制
所有的班级的乱码数据都贴好
''' 把孩子通复制出来的整页号码,Python删除空行,家长手机号码横向排列 爸爸或妈妈没有手机号,也空着 批量处理20个班级工作表 deepseek,阿夏 20261029 ''' import openpyxl import os import re from openpyxl.styles import Font, Alignment def process_single_sheet(ws): """处理单个工作表的函数,返回组装好的列表数据""" final_data = [] current_student = None # 从第2行开始遍历(跳过表头) for row in ws.iter_rows(min_row=2, values_only=True): row_values = [str(cell).strip() if cell is not None else "" for cell in row] if not any(row_values): continue row_text = "|".join(row_values) # ========================================== # 拦截无用行 # ========================================== if '已激活' in row_text or '未激活' in row_text: continue if re.search(r'[托小中大][一二三四五六123456]班', row_text): continue if any(kw in row_text for kw in ['学生称谓', '修改学生']): continue col_a = row_values[0] col_b = row_values[1] if len(row_values) > 1 else "" col_c = row_values[2] if len(row_values) > 2 else "" # ========================================== # 【核心升级】:扩充身份词库(覆盖截图中的所有亲属) # ========================================== roles = [ '妈妈', '爸爸', '爷爷', '奶奶', '外公', '外婆', '姥爷', '姥姥', '伯父', '伯母', '叔叔', '婶婶', '姑姑', '姑父', '舅舅', '舅母', '姐姐', '哥哥', '嫂嫂', '姨姨', '姨夫', '亲友', ] invalid_names = ['学生', '姓名', '学生姓名', '幼儿', '幼儿姓名', '称谓', '操作'] # 1. 识别姓名 if 2 <= len(col_a) <= 4 and all('\u4e00' <= char <= '\u9fa5' for char in col_a) \ and col_a not in roles and col_a not in invalid_names: # 遇到新名字,保存上一个学生 if current_student: final_data.append([current_student['id'], current_student['name']] + current_student['parents']) current_student = { 'id': '', 'name': col_a, 'parents': [] } continue # 2. 识别学号 match_sid = re.search(r'学号[::]\s*(\d+)', col_a) if match_sid and current_student: current_student['id'] = match_sid.group(1) continue # 3. 识别家长信息(使用扩充后的身份词库) if current_student and col_a in roles: current_student['parents'].extend([col_a, col_b, col_c]) # 把最后一个学生存进去 if current_student: final_data.append([current_student['id'], current_student['name']] + current_student['parents']) return final_data def process_all_sheets(): # ================= 配置区 ================= path = r'D:\000Python网页html\20261026破译电话号码' input_file = os.path.join(path, '孩子通提取所有班级的手机号码.xlsx') # 原文件 output_file = os.path.join(path, '全园班级_家长手机号码.xlsx') # ========================================= if not os.path.exists(input_file): print(f"❌ 找不到文件: {input_file}") return print("正在读取原始数据...") wb_in = openpyxl.load_workbook(input_file, data_only=True) out_wb = openpyxl.Workbook() out_wb.remove(out_wb.active) header_font = Font(bold=True) for sheet_name in wb_in.sheetnames: ws_in = wb_in[sheet_name] print(f"正在处理工作表:{sheet_name} ...") final_data = process_single_sheet(ws_in) if not final_data: print(f" ⚠️ {sheet_name} 未提取到有效数据,已跳过。") continue print(f" ✅ 提取到 {len(final_data)} 个学生。") ws_out = out_wb.create_sheet(title=sheet_name) # 构建表头 max_parent_len = max([len(row) - 2 for row in final_data]) if final_data else 0 headers = ["学号", "姓名"] for i in range(1, (max_parent_len // 3) + 1): headers.extend([f"身份{i}", f"号码{i}", f"编号{i}"]) for i in range(len(headers) - 2, max_parent_len): headers.append(f"信息{i+1}") ws_out.append(headers) # 写入数据 for row in final_data: ws_out.append(row) # 样式美化 for col_idx, cell in enumerate(ws_out[1], start=1): cell.font = header_font cell.alignment = Alignment(horizontal="center", vertical="center") max_len = len(str(cell.value)) for r_idx in range(2, ws_out.max_row + 1): val = str(ws_out.cell(row=r_idx, column=col_idx).value or "") if len(val) > max_len: max_len = len(val) ws_out.column_dimensions[openpyxl.utils.get_column_letter(col_idx)].width = max(max_len + 4, 12) try: out_wb.save(output_file) print(f"\n🎉 全部处理完成!") print(f"📁 文件已保存至: {output_file}") except Exception as e: print(f"❌ 保存失败: {e}") if __name__ == '__main__': process_all_sheets()