WhatsApp手术数据转Excel后无法按患者合并行的问题求助
解决WhatsApp手术数据合并到Excel同一行的问题
问题说明
需要将2020-2023年的医院敏感手术数据从WhatsApp导出到Excel,当前流程是通过PushBullet转成.txt文件后用Python清洗,但同一患者的手术字段(如*Fecha:、*Nombre:等)分散在不同行,无法合并到同一行对应列中。
简化解决方案(基于Pandas,易操作)
以下是整合了数据清洗和患者字段合并的完整代码,无需分两次处理文件,适合非专业人员使用:
import pandas as pd # 替换为你的WhatsApp导出txt文件路径 file_path = "your_whatsapp_export.txt" # 替换为你要保存的Excel文件路径 output_excel = "手术数据整理结果.xlsx" # 读取并处理txt文件 with open(file_path, mode='r', encoding="utf8") as f: data = f.readlines() # 跳过前4行冗余内容(和原逻辑一致) dataset = data[4:] # 定义消息字段与Excel列名的对应关系,可根据实际调整 field_mapping = { "*Programación:": "手术类型", "*Fecha:": "手术日期", "*Nombre:": "患者姓名", "*Patología:": "病理类型", "*Cirugía:": "手术名称", "*Cirujano:": "主刀医生", "*Primer Ayudante:": "第一助手", "*Segundo Ayudante:": "第二助手" } patients_data = [] current_patient = {} for line in dataset: if not line.strip(): continue # 提取消息核心内容(沿用原清洗逻辑) date = line.split(",")[0] line2 = line[len(date):] time = line2.split("-")[0][2:] line3 = line2[len(time):] name = line3.split(":")[0][4:] message = line3[len(name):][6:-1].strip() # 匹配字段并合并到当前患者数据 for field_key, column_name in field_mapping.items(): if message.startswith(field_key): field_value = message[len(field_key):].strip() # 以*Programación:作为新患者数据的起始标识,可替换为*Nombre:等 if field_key == "*Programación:": if current_patient: patients_data.append(current_patient) current_patient = { "消息日期": date, "消息时间": time, column_name: field_value } else: current_patient[column_name] = field_value break # 加入最后一位患者的数据 if current_patient: patients_data.append(current_patient) # 转换为Excel格式并保存 df = pd.DataFrame(patients_data) df.to_excel(output_excel, index=False, engine="openpyxl") print(f"数据已成功保存至:{output_excel}")
使用步骤
- 安装依赖库:打开电脑的命令提示符(CMD),输入以下命令安装所需工具:
pip install pandas openpyxl - 修改路径:将代码中的
file_path和output_excel替换为你自己的文件路径(注意路径用英文引号包裹)。 - 调整起始标识:如果WhatsApp中每组患者数据的第一条不是Programación:,而是Nombre:,只需把代码里的
if field_key == "*Programación:"改成if field_key == "*Nombre:"即可。 - 运行代码:执行脚本后,就能得到同一患者所有字段合并在同一行的Excel文件。
内容的提问来源于stack exchange,提问作者Dr.Razadyne
相关产品推荐
相关产品推荐

