Add pathology report scraper and lymphoma data enrichment scripts

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.
This commit is contained in:
2026-08-30 21:27:35 +08:00
commit 5510342628
6 changed files with 741 additions and 0 deletions
+11
View File
@@ -0,0 +1,11 @@
# deny-by-default: only the scraper/extraction scripts themselves go into this repo.
# All patient data, Excel outputs, JSON aggregates, and logs contain real PHI and must
# never be committed.
*
!/.gitignore
!/extract_pathology_reports.py
!/watch_progress.py
!/merge_pathology_json.py
!/fill_lymphoma_excel.py
!/README.md
+24
View File
@@ -0,0 +1,24 @@
# lymphoma-pathology-scraper
从内网病历/PACS系统批量抓取病理报告,并用抓取结果尽量补全淋巴瘤患者数据表格。
## 脚本说明
- **extract_pathology_reports.py** — 主抓取脚本。按病历号(住院号)+门诊号双重查询、按"病理"+"骨髓"两个检查类别搜索,去重合并后保存到 `患者报告/<病历号>/病理报告/`(一个汇总json+一个汇总txt+images目录)。抓取过程中把进度写入 `progress.json`,供 `watch_progress.py` 实时查看。
用法: `python extract_pathology_reports.py [患者数量上限,不填则跑全部]`
- **watch_progress.py** — 实时查看 `extract_pathology_reports.py` 的抓取进度(读 `progress.json`,定时刷新)。
用法: `python watch_progress.py [刷新间隔秒数,默认2]`
- **merge_pathology_json.py** — 把 `患者报告/<病历号>/病理报告/病理报告.json` 全部汇总成一个 `病理报告汇总.json`。
- **fill_lymphoma_excel.py** — 用 `病理报告汇总.json` 尽量补全淋巴瘤数据表格(IHC标志物、完整诊断、诊断日期、生发中心分型、骨髓侵犯、首发部位等),只填空白格子,不覆盖已有数据,并生成补全日志记录每个字段的来源报告。
## 依赖
- `http_scraper.py`(`HttpScaper` 类,位于 `all-codex - 副本` 目录)— 未包含在本仓库,需要单独放到 `sys.path` 能找到的位置。
- Python: `pandas`, `requests`, `openpyxl`
## 注意
本仓库只包含代码,不包含任何患者数据/Excel/JSON输出/日志(见 `.gitignore`)。脚本里的内网地址(病历系统、PACS系统等)仅在医院内网环境下可访问。
+329
View File
@@ -0,0 +1,329 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
批量抓取并保存病理报告(淋巴瘤数据)
- 病历号取自 Excel 表格中的 住院号 列(自动补 000 前缀)
- 按病历号(住院号)搜一次,再查出对应门诊号后按门诊号搜一次,两次结果按检查号去重合并
(部分病理检查是门诊开的单,只挂在门诊号下,仅按住院号搜会漏)
- 每个患者的所有报告合并保存为一个json+一个txt,图片统一放images子目录,不保存原始html
- 用法: python extract_pathology_reports.py [患者数量上限,不填则跑全部]
"""
import sys
sys.path.insert(0, r"C:\Users\senqu\Desktop\all-codex - 副本")
from http_scraper import HttpScaper
import re
import json
import html as html_lib
import pandas as pd
import requests
import time
import os
# 配置
EXCEL_PATH = r"C:\Users\senqu\Desktop\尚安迪\2026.8.25\淋巴瘤数据.xlsx"
OUTPUT_ROOT = r"C:\Users\senqu\Desktop\尚安迪\2026.8.25\患者报告"
PROGRESS_FILE = r"C:\Users\senqu\Desktop\尚安迪\2026.8.25\progress.json"
HIS_BASE_URL = 'http://129.1.163.23:8086'
ZZ_URL = 'http://129.1.177.108:8118/wfinpatientproof.aspx'
HOSPITAL_NO = '41580193-4'
def get_visit_max(his_session, patient_id):
"""获取患者最大住院次数(用于拼门诊号查询参数)"""
url = f'{HIS_BASE_URL}/?hospital_no={HOSPITAL_NO}&patient_id={patient_id}&visit_id=1'
resp = his_session.get(url, timeout=60)
resp.encoding = 'utf-8'
m = re.search(r'span_index_visitMax[^>]*>(\d+)', resp.text)
return int(m.group(1)) if m else 1
def get_outpatient_no(his_session, patient_id, visit_max):
"""从住院证页面查询该病历号对应的门诊号"""
patient_no = f'ZY{visit_max:02d}{patient_id}'
url = f'{ZZ_URL}?patient_no={patient_no}'
resp = his_session.get(url, timeout=30)
resp.encoding = 'utf-8'
m = re.search(r'id="alCardNO">(\d+)</span>', resp.text)
return m.group(1) if m else ''
# 检查类别下拉框里,"病理"和"骨髓"是两个独立类别(淋巴瘤患者常规做骨髓穿刺/活检,
# 这部分报告只挂在"骨髓"类别下,不在"病理"类别里),所以两个类别都要搜,缺一个就会漏。
EXAM_CLASSES = [("patho|9", "病理"), ("BoneMarrow|S", "骨髓")]
def search_by_clinicno_and_class(scraper, clinic_no, exam_class):
"""按病历号/门诊号(clinicno)搜索,限定检查类别为 exam_class
注意:不能先搜"全部"类别再本地过滤,因为搜索结果每页只有20条,
翻页按钮(goPage/lnkBtnNext)对该搜索会返回500错误、无法翻页,
older的报告会被截断丢失。直接在服务端按类别过滤可以避开这个问题。
"""
data = dict(scraper._form_fields)
for k in ("CB_Time", "__EVENTTARGET", "__EVENTARGUMENT"):
data.pop(k, None)
data.update({
"clinicno": clinic_no, "checkno": "", "CB_Info": "on",
"DDL_ExamClassItem": exam_class,
"IB_Search.x": "30", "IB_Search.y": "10",
})
resp = scraper.session.post("http://129.1.58.7:5001/Pages/HISToPacs.aspx", data=data, timeout=15)
resp.encoding = "gbk"
scraper._update_form_fields(resp.text)
return resp.text
def get_total_pages(html_text):
m = re.search(r'id="lblSumPage"[^>]*>([^<]*)<', html_text)
if m and m.group(1).strip().isdigit():
return int(m.group(1).strip())
return 1
def search_pathology_records(scraper, clinic_no):
"""对病理+骨髓两个类别分别搜索并合并,返回(报告列表, 是否有截断)"""
all_records = []
truncated = False
for exam_class, class_label in EXAM_CLASSES:
ht = search_by_clinicno_and_class(scraper, clinic_no, exam_class)
if scraper.has_no_records(ht):
continue
records = scraper.parse_result_table(ht)
for r in records:
r['检查类别'] = class_label
all_records.extend(records)
if get_total_pages(ht) > 1:
truncated = True
return all_records, truncated
def extract_report_details(scraper, report_url):
"""抓取报告详情页,解析出影像表现/印象/图片URL"""
try:
resp = scraper.session.get(f"http://129.1.58.7:5001/Pages/{report_url}", timeout=8)
resp.encoding = "gbk"
html_text = resp.text
result = {"影像表现": "", "印象": "", "raw_html": html_text, "image_urls": []}
hd_raw = re.search(r'name="hd_images"[^>]*value="([^"]*)"', html_text)
if hd_raw:
images = json.loads(html_lib.unescape(hd_raw.group(1)))
if images:
result["影像表现"] = (images[0].get("Describe") or "").strip()
result["印象"] = (images[0].get("Diagnosis") or "").strip()
result["images_data"] = images
for img in images:
u = img.get("ImgUrl", "")
if u:
result["image_urls"].append(f"http://129.1.58.7:5001/Pages/{u}")
if not result["印象"] and not result["影像表现"]:
hd_r = re.search(r'name="hdReportMsg"[^>]*value="([^"]*)"', html_text)
if hd_r:
reports = json.loads(html_lib.unescape(hd_r.group(1)))
if reports:
result["影像表现"] = (reports[0].get("examdesc") or "").strip()
result["印象"] = (reports[0].get("examdiagnosis") or "").strip()
if not result["印象"]:
m = re.search(r'<textarea[^>]*id="TB_YX"[^>]*>(.*?)</textarea>', html_text, re.S | re.I)
if m and m.group(1).strip():
result["印象"] = m.group(1).strip()
if not result["影像表现"]:
m = re.search(r'<textarea[^>]*id="TB_YXBX"[^>]*>(.*?)</textarea>', html_text, re.S | re.I)
if m and m.group(1).strip():
result["影像表现"] = m.group(1).strip()
return result
except Exception as e:
return {"影像表现": "", "印象": "", "error": str(e), "image_urls": []}
def download_image(scraper, img_url, save_path):
"""下载报告中的图片"""
try:
resp = scraper.session.get(img_url, timeout=15)
if resp.status_code == 200 and len(resp.content) > 100:
with open(save_path, 'wb') as f:
f.write(resp.content)
return True
except Exception:
pass
return False
def save_patient_reports(patient_dir, report_type, items, scraper):
"""合并保存一个患者的所有报告:
- 一个汇总 json(列表)+ 一个汇总 txt(分隔拼接)
- 所有图片平铺存到 images/ 子目录(按检查号_序号命名,避免重名)
- 不保存原始html
items: [(report_info, details), ...]
"""
d = os.path.join(patient_dir, report_type)
os.makedirs(d, exist_ok=True)
img_dir = os.path.join(d, 'images')
all_json = []
txt_parts = []
for report_info, details in items:
check_no = re.sub(r'[<>:"/\\|?*]', '', report_info.get('检查号', '') or 'noid')
txt_parts.append(
f"检查号: {check_no}\n"
f"检查项目: {report_info.get('检查项目', '')}\n"
f"检查类别: {report_info.get('检查类别', '')}\n"
f"查询类型: {report_info.get('查询类型', '')}\n"
f"检查部位: {report_info.get('检查部位', '')}\n"
f"检查时间: {report_info.get('检查时间', '')}\n\n"
f"=== 影像表现 ===\n{details.get('影像表现', '')}\n\n"
f"=== 印象/诊断 ===\n{details.get('印象', '')}\n"
)
jd = {'report_info': report_info, '影像表现': details.get('影像表现', ''), '印象': details.get('印象', '')}
if 'images_data' in details:
jd['images_data'] = details['images_data']
all_json.append(jd)
if details.get('image_urls'):
os.makedirs(img_dir, exist_ok=True)
for i, u in enumerate(details['image_urls']):
download_image(scraper, u, os.path.join(img_dir, f"{check_no}_{i + 1}.jpg"))
with open(os.path.join(d, f"{report_type}.json"), 'w', encoding='utf-8') as f:
json.dump(all_json, f, ensure_ascii=False, indent=2)
with open(os.path.join(d, f"{report_type}.txt"), 'w', encoding='utf-8') as f:
f.write(('\n' + '=' * 60 + '\n').join(txt_parts))
def get_medical_record_no(row):
"""病历号:住院号列补000前缀"""
return "000" + str(int(row['住院号'])).zfill(7)
def write_progress(processed, total, stats, current_patient, start_time, done=False):
"""把当前进度写入json文件,供 watch_progress.py 实时读取展示"""
data = {
'total': total,
'processed': processed,
'current_patient': current_patient,
'start_time': start_time,
'updated_at': time.time(),
'elapsed_sec': time.time() - start_time,
'done': done,
**stats,
}
tmp_path = PROGRESS_FILE + '.tmp'
with open(tmp_path, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
os.replace(tmp_path, PROGRESS_FILE)
# ===== MAIN =====
def main():
limit = int(sys.argv[1]) if len(sys.argv) > 1 else None
df = pd.read_excel(EXCEL_PATH, sheet_name=0)
if limit:
df = df.head(limit)
os.makedirs(OUTPUT_ROOT, exist_ok=True)
scraper = HttpScaper()
his_session = requests.Session()
his_session.trust_env = False
total = len(df)
print(f"开始抓取 {total} 个患者的病理报告(住院号+门诊号双重查询)...")
start_time = time.time()
stats = {
'success': 0, 'no_record': 0, 'no_patho': 0, 'failed': 0,
'report_count': 0, 'truncated': 0, 'outpatient_found': 0,
'outpatient_extra_reports': 0,
}
write_progress(0, total, stats, '', start_time)
for idx, row in df.iterrows():
cn = get_medical_record_no(row)
if (idx + 1) % 50 == 0:
print(f"进度: {idx + 1}/{total} ({time.time() - start_time:.0f}秒)")
try:
# 1) 按病历号(住院号)搜索(病理+骨髓两个类别)
prs, truncated = search_pathology_records(scraper, cn)
for r in prs:
r['查询类型'] = '住院'
if truncated:
print(f" [{cn}] 警告: 按住院号搜到的某个类别报告超过1页,只抓取了第1页,可能有遗漏!")
stats['truncated'] += 1
# 2) 查询门诊号,按门诊号再搜一次,去重合并
try:
visit_max = get_visit_max(his_session, cn)
mzh = get_outpatient_no(his_session, cn, visit_max)
except Exception as e:
mzh = ''
print(f" [{cn}] 获取门诊号失败: {e}")
if mzh:
stats['outpatient_found'] += 1
prs2, truncated2 = search_pathology_records(scraper, mzh)
if truncated2:
print(f" [{cn}] 警告: 按门诊号{mzh}搜到的某个类别报告超过1页,只抓取了第1页,可能有遗漏!")
existing_nos = {r.get('检查号') for r in prs}
for r in prs2:
if r.get('检查号') not in existing_nos:
r['查询类型'] = '门诊'
prs.append(r)
existing_nos.add(r.get('检查号'))
stats['outpatient_extra_reports'] += 1
if not prs:
stats['no_patho'] += 1
continue
pd_dir = os.path.join(OUTPUT_ROOT, cn)
os.makedirs(pd_dir, exist_ok=True)
items = []
for p in prs:
d = extract_report_details(scraper, p['报告链接'])
items.append((p, d))
stats['report_count'] += 1
save_patient_reports(pd_dir, "病理报告", items, scraper)
stats['success'] += 1
print(f" [{cn}] 保存 {len(prs)} 份病理报告(门诊号={mzh or '无'})")
except Exception as e:
print(f" [{cn}] 处理失败: {e}")
stats['failed'] += 1
write_progress(idx + 1, total, stats, cn, start_time)
time.sleep(0.2)
scraper.close()
write_progress(total, total, stats, '', start_time, done=True)
print(f"\n{'=' * 60}")
print(f"完成!耗时: {time.time() - start_time:.0f}秒")
print(f"总患者数: {total}")
print(f"有病理报告的患者: {stats['success']}")
print(f"无检查记录/无病理报告: {stats['no_record'] + stats['no_patho']}")
print(f"抓取失败: {stats['failed']}")
print(f"病理报告总数: {stats['report_count']}")
print(f"找到门诊号的患者: {stats['outpatient_found']}")
print(f"通过门诊号额外补到的报告数: {stats['outpatient_extra_reports']}")
print(f"可能有遗漏(单次搜索超过20条/1页)的患者: {stats['truncated']}")
print(f"报告保存路径: {OUTPUT_ROOT}\\<病历号>\\病理报告\\")
if __name__ == '__main__':
main()
+250
View File
@@ -0,0 +1,250 @@
#!/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()
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""把 患者报告\<病历号>\病理报告\病理报告.json 全部汇总成一个json文件"""
import json
import os
OUTPUT_ROOT = r"C:\Users\senqu\Desktop\尚安迪\2026.8.25\患者报告"
MERGED_PATH = r"C:\Users\senqu\Desktop\尚安迪\2026.8.25\病理报告汇总.json"
def main():
merged = {}
patient_count = 0
report_count = 0
for cn in sorted(os.listdir(OUTPUT_ROOT)):
json_path = os.path.join(OUTPUT_ROOT, cn, "病理报告", "病理报告.json")
if not os.path.isfile(json_path):
continue
with open(json_path, 'r', encoding='utf-8') as f:
reports = json.load(f)
if not reports:
continue
merged[cn] = reports
patient_count += 1
report_count += len(reports)
with open(MERGED_PATH, 'w', encoding='utf-8') as f:
json.dump(merged, f, ensure_ascii=False, indent=2)
print(f"汇总完成: {patient_count} 个患者, {report_count} 份报告")
print(f"输出文件: {MERGED_PATH}")
if __name__ == '__main__':
main()
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
实时查看 extract_pathology_reports.py 的抓取进度
用法: python watch_progress.py [刷新间隔秒数,默认2]
"""
import json
import os
import time
import sys
PROGRESS_FILE = r"C:\Users\senqu\Desktop\尚安迪\2026.8.25\progress.json"
def fmt_time(sec):
sec = int(sec)
h, rem = divmod(sec, 3600)
m, s = divmod(rem, 60)
if h:
return f"{h}时{m}分{s}秒"
if m:
return f"{m}分{s}秒"
return f"{s}秒"
def main():
interval = float(sys.argv[1]) if len(sys.argv) > 1 else 2.0
while True:
if not os.path.exists(PROGRESS_FILE):
print("等待任务启动...(还没有 progress.json)")
time.sleep(interval)
continue
try:
with open(PROGRESS_FILE, 'r', encoding='utf-8') as f:
data = json.load(f)
except (json.JSONDecodeError, OSError):
time.sleep(0.5)
continue
processed = data.get('processed', 0)
total = data.get('total', 0)
elapsed = data.get('elapsed_sec', 0)
done = data.get('done', False)
os.system('cls' if os.name == 'nt' else 'clear')
pct = (processed / total * 100) if total else 0
rate = processed / elapsed if elapsed > 0 else 0
remaining = (total - processed) / rate if rate > 0 else 0
bar_len = 40
filled = int(bar_len * pct / 100)
print("=" * 60)
print("病理报告抓取进度")
print("=" * 60)
print(f"进度: {processed}/{total} ({pct:.1f}%)")
print("[" + "#" * filled + "-" * (bar_len - filled) + "]")
print()
print(f"当前患者: {data.get('current_patient', '') or '(已完成)'}")
print(f"已用时间: {fmt_time(elapsed)}")
if not done and rate > 0:
print(f"预计剩余: {fmt_time(remaining)} (速度: {rate:.2f}人/秒)")
print()
print(f"有病理报告的患者: {data.get('success', 0)}")
print(f"无病理报告: {data.get('no_patho', 0)}")
print(f"抓取失败: {data.get('failed', 0)}")
print(f"病理报告总数: {data.get('report_count', 0)}")
print(f"找到门诊号的患者: {data.get('outpatient_found', 0)}")
print(f"门诊号额外补到的报告数: {data.get('outpatient_extra_reports', 0)}")
print(f"可能截断(单次超20条/1页): {data.get('truncated', 0)}")
print()
if done:
print("=" * 60)
print("任务已完成!")
break
print(f"(每{interval}秒自动刷新,Ctrl+C退出)")
time.sleep(interval)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("\n已停止监控。")