我编写了以下函数来使用Entrez从PubMed中提取数据:
def getFromPubMed(id):
handle = Entrez.efetch(db="pubmed",rettype="medline",retmode="text", id=str(id))
records = Medline.parse(handle)
for record in records:
abstract = str(record["AB"])
mesh = str(record["MH"]).replace("'", "").replace("[", "").replace("]", "")
pmid = str(record["PMID"])
title = str(record["TI"]).replace("'", "").replace("[", "").replace("]", "")
pt = str(record["PT"]).replace("'", "").replace("[", "").replace("]", "")
au = str(record["AU"])
dp = str(record["DP"])
la = str(record["LA"])
pmc = str(record["PMC"])
si = str(record["SI"])
try:
doi=str(record["AID"])
except:
doi = str(record["SO"]).split('doi:',1)[1]
return pmid, title, abstract, au, mesh, doi, pt, la, pmc但是,此函数并不总是工作,因为并非所有MEDLINE记录都包含所有字段。例如,这个PMID不包含任何MeSH标题。
我可以用一个try- for语句包装每一项,例如对于abstract。
try:
abstract = str(record["AB"])
except:
abstract = ""但这似乎是实现这一目标的一种笨拙的方式。更优雅的解决方案是什么?
发布于 2018-02-03 02:46:29
您可以将提取字段的操作拆分为单独的方法--执行如下操作:
def get_record_attributes(record, attr_details):
attributes = {}
for attr_name, details in attr_details.items():
value = ""
try:
value = record[details["key"]]
for char in details["chars_to_remove"]:
value = value.replace(char, "")
except KeyError, AttributeError:
pass
attributes[attr_name] = value
return attributes
def getFromPubMed(id):
handle = Entrez.efetch(db="pubmed",rettype="medline",retmode="text", id=str(id))
records = Medline.parse(handle)
for record in records:
attr_details = {
"abstract" : {"key" : "AB"},
"mesh" : { "key" : "MH", "chars_to_remove" : "'[]"},
#...
"aid" : {"key" : "AB"},
"so" : {"key" : "SO"},
}
attributes = get_record_attributes(record, attr_details)
#...发布于 2018-02-03 20:32:06
https://stackoverflow.com/questions/48593234
复制相似问题