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
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
HMDB Kidney 代谢物筛选工具
作者:IT小章
时间:2026年4月8日
网站:itxiaozhang.com
功能:从HMDB XML数据库中筛选与肾脏相关的代谢物,并过滤Excel文件
"""
import argparse
import csv
import os
import re
import time
from lxml import etree
# 默认XML路径
DEFAULT_XML_PATH = r"C:\Users\Administrator\Documents\HMDB离线数据库\hmdb_metabolites\hmdb_metabolites.xml"
def normalize_hmdb_id(raw: str) -> str | None:
"""标准化HMDB ID格式为 HMDB0000001"""
if not raw:
return None
s = raw.strip().upper()
m = re.match(r"^HMDB(\d+)$", s)
if not m:
return None
return "HMDB" + m.group(1).zfill(7)
def detect_namespace(xml_file: str) -> str:
"""检测XML命名空间"""
with open(xml_file, "rb") as f:
context = etree.iterparse(f, events=("start",))
_, root = next(context)
if "}" in root.tag:
return root.tag.split("}", 1)[0][1:]
return ""
def has_kidney_keyword(elem, ns: str) -> bool:
"""检查代谢物是否包含kidney关键词"""
tag = lambda local: f"{{{ns}}}{local}" if ns else local
# 检查组织位置
bio = elem.find(tag("biological_properties"))
if bio is not None:
tissues = bio.find(tag("tissue_locations"))
if tissues is not None:
for t in tissues.findall(tag("tissue")):
if "kidney" in (t.text or "").lower():
return True
# 检查本体论
ontology = elem.find(tag("ontology"))
if ontology is not None:
for t in ontology.iter(tag=tag("term")):
if "kidney" in (t.text or "").lower():
return True
return False
def build_kidney_set(xml_file: str) -> set[str]:
"""构建肾脏相关代谢物ID集合"""
print(f"正在解析 XML: {xml_file}")
ns = detect_namespace(xml_file)
tag = lambda local: f"{{{ns}}}{local}" if ns else local
kidney_ids = set()
count = 0
start = time.time()
context = etree.iterparse(xml_file, events=("end",), tag=tag("metabolite"))
for _, elem in context:
count += 1
if count % 5000 == 0:
rate = count / (time.time() - start)
print(f" 已扫描 {count} 条,命中 {len(kidney_ids)} 条 ({rate:.0f} 条/秒)")
if has_kidney_keyword(elem, ns):
# 提取主ID
acc = elem.find(tag("accession"))
if acc is not None and acc.text:
if (nid := normalize_hmdb_id(acc.text)):
kidney_ids.add(nid)
# 提取次要ID
sec = elem.find(tag("secondary_accessions"))
if sec is not None:
for a in sec.findall(tag("accession")):
if (nid := normalize_hmdb_id(a.text)):
kidney_ids.add(nid)
# 释放内存
elem.clear()
while elem.getprevious() is not None:
del elem.getparent()[0]
print(f"XML解析完成: 共 {count} 条代谢物,{len(kidney_ids)} 条与肾脏相关")
return kidney_ids
def find_hmdb_column(headers: list) -> int:
"""查找HMDB ID所在列索引(从1开始)"""
norm = lambda x: str(x).lower().replace("_", " ").replace("-", " ")
candidates = {"hmdb id", "hmdbid", "compound id", "compoundid"}
for i, h in enumerate(headers, 1):
if norm(h) in candidates:
return i
return 2 # 默认第2列
def filter_excel(src_path: str, out_path: str, kidney_set: set) -> dict:
"""过滤Excel文件,只保留肾脏相关行"""
import openpyxl
wb = openpyxl.load_workbook(src_path, read_only=True, data_only=False)
stats = {"in": 0, "out": 0, "removed": 0}
with open(out_path, "w", encoding="utf-8-sig", newline="") as f:
writer = csv.writer(f, lineterminator="\n")
for sheet in wb.sheetnames:
ws = wb[sheet]
hmdb_col = find_hmdb_column([c.value for c in next(ws.iter_rows(max_row=1))])
max_col = ws.max_column or 0
print(f" 处理工作表 '{sheet}' (HMDB列: {hmdb_col})")
for i, row in enumerate(ws.iter_rows(values_only=False)):
stats["in"] += 1
# 保留表头
if i == 0:
writer.writerow([c.value for c in row])
stats["out"] += 1
continue
# 检查HMDB ID
try:
raw_id = row[hmdb_col - 1].value
except IndexError:
raw_id = None
nid = normalize_hmdb_id(str(raw_id)) if raw_id else None
# 匹配则保留,否则跳过
if nid and nid in kidney_set:
writer.writerow([c.value for c in row])
stats["out"] += 1
else:
stats["removed"] += 1
return stats
def main():
parser = argparse.ArgumentParser(description="HMDB肾脏代谢物筛选工具")
parser.add_argument("--xml", default=DEFAULT_XML_PATH, help="HMDB XML文件路径")
parser.add_argument("--xlsx-dir", default="data", help="输入Excel目录")
parser.add_argument("--suffix", default=".kidney", help="输出文件后缀")
args = parser.parse_args()
if not os.path.exists(args.xml):
raise SystemExit(f"错误: 找不到XML文件 {args.xml}")
if not os.path.isdir(args.xlsx_dir):
raise SystemExit(f"错误: 找不到目录 {args.xlsx_dir}")
# 步骤1: 构建肾脏代谢物集合
kidney_set = build_kidney_set(args.xml)
# 步骤2: 处理Excel文件
print(f"\n开始处理Excel文件 (目录: {args.xlsx_dir})")
for name in sorted(os.listdir(args.xlsx_dir)):
if not name.endswith(".xlsx") or args.suffix in name:
continue
src = os.path.join(args.xlsx_dir, name)
out = os.path.join(args.xlsx_dir, name[:-5] + args.suffix + ".csv")
print(f"\n处理: {name}")
start = time.time()
stats = filter_excel(src, out, kidney_set)
print(f"完成: 输入 {stats['in']} 行, 输出 {stats['out']} 行, 跳过 {stats['removed']} 行")
print(f"输出: {out} ({time.time()-start:.1f}s)")
print("\n全部完成!")
if __name__ == "__main__":
main()
|