Scripts for batch-scraping pathology reports from the hospital PACS system (by inpatient + outpatient number, across pathology and bone marrow exam categories) and using the results to fill in blank fields in a lymphoma patient dataset.
251 lines
10 KiB
Python
251 lines
10 KiB
Python
#!/usr/bin/env python
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
用病理报告汇总JSON尽量补全 淋巴瘤数据.xlsx 的空白字段
|
||
|
||
规则:
|
||
- 一个患者可能有多份病理报告(同一次活检的不同组织块 bc_1/bc_2/... ,或不同时间的多次活检)
|
||
同一检查号内部可能有"第一次报告/第二次报告/..."多段修订,只取最后一段(最终结论)
|
||
多个检查号若检查时间相同,视为同一次活检的不同组织块,合并处理
|
||
- 取"最早一次"含明确淋巴瘤诊断结论的活检(时间分组),从中提取:
|
||
完整诊断、诊断日期、IHC标志物(Bcl-6/Bcl-2/P53/Ki-67/C-myc/MUM-1/CD3/CD5/CD10/EBER/CyclinD1)、
|
||
生发中心/非生发中心(仅报告明确写出时才填)、首发部位/结内1结外0/结外(低置信度,日志标注)
|
||
- 骨髓侵犯: 取最早一份"骨髓"类别报告,按关键词判断阳性/阴性
|
||
- 只填表格里当前为空的格子,不覆盖已有数据
|
||
- 输出: 淋巴瘤数据_已补全.xlsx + 补全日志.txt(记录每个字段的来源报告和原文片段)
|
||
"""
|
||
|
||
import json
|
||
import re
|
||
import pandas as pd
|
||
|
||
MERGED_JSON = r"C:\Users\senqu\Desktop\尚安迪\2026.8.25\病理报告汇总.json"
|
||
EXCEL_PATH = r"C:\Users\senqu\Desktop\尚安迪\2026.8.25\淋巴瘤数据.xlsx"
|
||
OUTPUT_EXCEL = r"C:\Users\senqu\Desktop\尚安迪\2026.8.25\淋巴瘤数据_已补全.xlsx"
|
||
LOG_PATH = r"C:\Users\senqu\Desktop\尚安迪\2026.8.25\补全日志.txt"
|
||
|
||
MARKER_PATTERNS = {
|
||
'Bcl-6': r'Bcl-?6',
|
||
'Bcl-2': r'Bcl-?2',
|
||
'P53': r'P53',
|
||
'Ki-67': r'Ki-?67',
|
||
'C-myc': r'[Cc]-?[Mm]yc',
|
||
'MUM-1': r'MUM-?1',
|
||
'CD3': r'CD3(?!\d)',
|
||
'CD5': r'CD5(?!\d)',
|
||
'CD10': r'CD10(?!\d)',
|
||
'EBER': r'EBER',
|
||
'CyclinD1': r'Cyclin\s*D1',
|
||
}
|
||
|
||
DIAGNOSIS_KEYWORDS = ['淋巴瘤', 'Lymphoma', '霍奇金']
|
||
NODAL_KEYWORD = '淋巴结'
|
||
|
||
|
||
def parse_dt(t):
|
||
try:
|
||
return pd.to_datetime(t)
|
||
except Exception:
|
||
return pd.Timestamp.max
|
||
|
||
|
||
def split_final_segment(text):
|
||
"""同一检查号内"第一次报告/第二次报告/..."多段修订,取最后一段(最终结论)"""
|
||
parts = re.split(r'第[一二三四五六七八九十\d]+次报告[::]', text)
|
||
return parts[-1].strip() if parts else text.strip()
|
||
|
||
|
||
def extract_markers(text):
|
||
found = {}
|
||
for name, pat in MARKER_PATTERNS.items():
|
||
m = re.search(pat + r'\s*[((]\s*([^)()]{1,20})[))]', text)
|
||
if m:
|
||
found[name] = m.group(1).strip()
|
||
return found
|
||
|
||
|
||
def extract_gcb(text):
|
||
if '非生发中心' in text:
|
||
return '非生发中心'
|
||
if '生发中心' in text:
|
||
return '生发中心'
|
||
return ''
|
||
|
||
|
||
def extract_site(text):
|
||
"""从诊断行开头的括号里提取标本部位,如"(右颈部肿物)..."->"右颈部肿物"。
|
||
锚定在行首,避免匹配到行内其它无关括号内容。"""
|
||
m = re.match(r'^[((]([^)()]{2,20})[))]', text.strip())
|
||
return m.group(1).strip() if m else ''
|
||
|
||
|
||
def group_pathology_by_time(reports):
|
||
"""病理类别报告按检查时间分组:同一时间戳=同一次活检的不同组织块"""
|
||
groups = {}
|
||
for r in reports:
|
||
info = r.get('report_info', {})
|
||
if info.get('检查类别') != '病理':
|
||
continue
|
||
t = info.get('检查时间', '')
|
||
groups.setdefault(t, []).append(r)
|
||
return groups
|
||
|
||
|
||
def process_patient(reports):
|
||
"""返回 (fields_dict, log_lines)"""
|
||
fields = {}
|
||
log_lines = []
|
||
|
||
groups = group_pathology_by_time(reports)
|
||
sorted_times = sorted(groups.keys(), key=parse_dt)
|
||
|
||
for t in sorted_times:
|
||
blocks = groups[t]
|
||
final_segments = []
|
||
for r in blocks:
|
||
text = (r.get('影像表现', '') + '\n' + r.get('印象', '')).strip()
|
||
seg = split_final_segment(text)
|
||
check_no = r.get('report_info', {}).get('检查号', '')
|
||
final_segments.append((check_no, seg))
|
||
|
||
group_text = '\n'.join(seg for _, seg in final_segments)
|
||
if not any(kw in group_text for kw in DIAGNOSIS_KEYWORDS):
|
||
continue
|
||
|
||
# 找到最早确诊的分组,开始提取
|
||
diag_candidates = [(cn, seg) for cn, seg in final_segments if any(kw in seg for kw in DIAGNOSIS_KEYWORDS)]
|
||
best_cn, best_seg = max(diag_candidates, key=lambda x: len(x[1]))
|
||
|
||
# best_seg第一行经常只是复检日期戳(如"(2023.1.7)"),不是真正的诊断句,
|
||
# 要找到第一条含"淋巴瘤"关键词的行才是诊断结论
|
||
diag_line = ''
|
||
for line in best_seg.strip().split('\n'):
|
||
line = line.strip()
|
||
if line and any(kw in line for kw in DIAGNOSIS_KEYWORDS):
|
||
diag_line = line
|
||
break
|
||
if not diag_line:
|
||
diag_line = best_seg.strip().split('\n')[0]
|
||
|
||
fields['诊断日期'] = str(t).split(' ')[0]
|
||
fields['完整诊断'] = diag_line
|
||
log_lines.append(f" [诊断日期/完整诊断] 来自检查号{best_cn} 检查时间{t}")
|
||
log_lines.append(f" 原文: {diag_line[:200]}")
|
||
|
||
markers = extract_markers(group_text)
|
||
for name, val in markers.items():
|
||
fields[name] = val
|
||
if markers:
|
||
log_lines.append(f" [IHC标志物] 来自检查时间{t}分组: {markers}")
|
||
|
||
gcb = extract_gcb(group_text)
|
||
if gcb:
|
||
fields['生发中心/非生发中心'] = gcb
|
||
log_lines.append(f" [生发中心/非生发中心]={gcb} 来自检查时间{t}分组")
|
||
|
||
site = extract_site(diag_line)
|
||
if site:
|
||
fields['首发部位'] = site
|
||
fields['结内1/结外0'] = 1 if NODAL_KEYWORD in site else 0
|
||
if NODAL_KEYWORD not in site:
|
||
fields['结外'] = site
|
||
log_lines.append(f" [首发部位/结内结外](低置信度-待核实)从\"{site}\"推断,来自检查号{best_cn}")
|
||
|
||
break # 只用最早一次确诊的活检
|
||
|
||
# 骨髓侵犯: 最早一份骨髓类别报告
|
||
# 注意: 这类报告多为常规骨髓涂片形态学报告(粒系/红系/巨核系分类计数),
|
||
# 很少直接写"浸润/累及"这种病理学术语,而是报"原始淋巴细胞/幼淋巴细胞"占比,
|
||
# 这类异常幼稚淋巴细胞的出现才是骨髓受累的关键信号。
|
||
bm_reports = [r for r in reports if r.get('report_info', {}).get('检查类别') == '骨髓']
|
||
if bm_reports:
|
||
bm_reports.sort(key=lambda r: parse_dt(r.get('report_info', {}).get('检查时间', '')))
|
||
bm = bm_reports[0]
|
||
bm_text = (bm.get('影像表现', '') + '\n' + bm.get('印象', '')).strip()
|
||
bm_check_no = bm.get('report_info', {}).get('检查号', '')
|
||
if re.search(r'(原始淋巴细胞|原淋|幼淋巴细胞|幼淋)', bm_text):
|
||
fields['骨髓侵犯'] = 1
|
||
log_lines.append(f" [骨髓侵犯]=1(阳性-见原始/幼稚淋巴细胞) 来自骨髓报告{bm_check_no}")
|
||
elif re.search(r'(浸润|累及|可见.{0,10}淋巴瘤|异常淋巴细胞|符合.{0,10}淋巴瘤)', bm_text) \
|
||
and not re.search(r'未见.{0,15}(浸润|累及|肿瘤细胞|淋巴瘤|异常)', bm_text):
|
||
fields['骨髓侵犯'] = 1
|
||
log_lines.append(f" [骨髓侵犯]=1(阳性) 来自骨髓报告{bm_check_no}")
|
||
elif re.search(r'未见.{0,15}(浸润|累及|肿瘤细胞|淋巴瘤|异常)', bm_text):
|
||
fields['骨髓侵犯'] = 0
|
||
log_lines.append(f" [骨髓侵犯]=0(阴性-报告明确排除) 来自骨髓报告{bm_check_no}")
|
||
elif re.search(r'淋巴细胞.{0,10}(形态大致正常|形态正常)', bm_text):
|
||
fields['骨髓侵犯'] = 0
|
||
log_lines.append(f" [骨髓侵犯]=0(推断阴性-常规骨髓象未见异常幼稚细胞,低置信度) 来自骨髓报告{bm_check_no}")
|
||
|
||
return fields, log_lines
|
||
|
||
|
||
def main():
|
||
with open(MERGED_JSON, 'r', encoding='utf-8') as f:
|
||
merged = json.load(f)
|
||
|
||
df = pd.read_excel(EXCEL_PATH, sheet_name=0)
|
||
columns = set(df.columns)
|
||
|
||
# 目标字段原本多是空列(float64 NaN),写入字符串/整数前先转成object类型,避免dtype警告
|
||
target_fields = [
|
||
'诊断日期', '完整诊断', '生发中心/非生发中心', 'Bcl-6', 'Bcl-2', 'P53', 'Ki-67',
|
||
'C-myc', 'MUM-1', 'CD3', 'CD5', 'CD10', 'EBER', 'CyclinD1',
|
||
'首发部位', '结内1/结外0', '结外', '骨髓侵犯',
|
||
]
|
||
for col in target_fields:
|
||
if col in df.columns:
|
||
df[col] = df[col].astype('object')
|
||
|
||
field_fill_count = {}
|
||
patient_filled_count = 0
|
||
log_blocks = []
|
||
|
||
for idx, row in df.iterrows():
|
||
cn = "000" + str(int(row['住院号'])).zfill(7)
|
||
if cn not in merged:
|
||
continue
|
||
|
||
fields, log_lines = process_patient(merged[cn])
|
||
if not fields:
|
||
continue
|
||
|
||
patient_log = [f"=== {cn} ==="]
|
||
any_written = False
|
||
for col, val in fields.items():
|
||
if col not in columns:
|
||
continue
|
||
cur = df.at[idx, col]
|
||
if pd.isna(cur):
|
||
df.at[idx, col] = val
|
||
field_fill_count[col] = field_fill_count.get(col, 0) + 1
|
||
any_written = True
|
||
else:
|
||
patient_log.append(f" [跳过] {col} 已有值({cur}),未覆盖,新值本来是: {val}")
|
||
|
||
if any_written:
|
||
patient_filled_count += 1
|
||
patient_log.extend(log_lines)
|
||
log_blocks.append('\n'.join(patient_log))
|
||
|
||
df.to_excel(OUTPUT_EXCEL, index=False)
|
||
|
||
with open(LOG_PATH, 'w', encoding='utf-8') as f:
|
||
f.write(f"补全统计: {patient_filled_count} 个患者有字段被补全\n")
|
||
f.write("各字段补全数:\n")
|
||
for col, cnt in sorted(field_fill_count.items(), key=lambda x: -x[1]):
|
||
f.write(f" {col}: {cnt}\n")
|
||
f.write("\n" + "=" * 60 + "\n\n")
|
||
f.write('\n\n'.join(log_blocks))
|
||
|
||
print(f"补全完成: {patient_filled_count} 个患者有字段被补全")
|
||
print("各字段补全数:")
|
||
for col, cnt in sorted(field_fill_count.items(), key=lambda x: -x[1]):
|
||
print(f" {col}: {cnt}")
|
||
print(f"\n输出Excel: {OUTPUT_EXCEL}")
|
||
print(f"补全日志: {LOG_PATH}")
|
||
|
||
|
||
if __name__ == '__main__':
|
||
main()
|