在 Python 中解析 MeSH ASCII 格式
与我们之前发布的 UniProt 解析器类似,MeSH 提供了可以使用 Python 轻松解析的 ASCII 格式。
就像 UniProt 解析器一样,此函数生成由字典表示的 MeSH 条目。文件底部包含示例代码。
mesh_parser.py
#!/usr/bin/env python3
"""
MeSH ASCII 格式的简单解析器,可从此处下载:
ftp://nlmpubs.nlm.nih.gov/online/mesh/.asciimesh/d2015.bin
有关 MeSH 标题(即结果映射中的键)的参考,请参见
https://www.nlm.nih.gov/mesh/meshhome.html
最初发布在 TechOverflow.net
"""
from collections import defaultdict
__author__ = "Uli Köhler"
__copyright__ = "Copyright 2015, Uli Köhler"
__license__ = "CC0 1.0 Universal"
__version__ = "1.0"
def readMeSH(fin):
"""
给定类文件对象,生成 MeSH 对象,即
每个限定符具有值列表的字典。
示例:{"MH": ["Acetylcysteine"]}
"""
currentEntry = None
for line in fin:
line = line.strip()
if not line:
continue
# 处理新记录。MeSH 明确标记此
if line == "*NEWRECORD":
# 生成旧条目,初始化新条目
if currentEntry:
yield currentEntry
currentEntry = defaultdict(list)
continue
# 行示例:"MH = Acetylcysteine"
key, _, value = line.partition(" = ")
# 追加到值列表
currentEntry[key].append(value)
# 如果还有非空条目,生成它
if currentEntry:
yield currentEntry
if __name__ == "__main__":
# 如何使用 readMeSH() 的示例
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("file")
args = parser.parse_args()
with open(args.file, "r") as infile:
# readMeSH() 生成 MeSH 对象,即字典
for entry in readMeSH(infile):
print(entry)Check out similar posts by category:
Bioinformatics, Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow