我正在尝试使用bibtex
的{{1}}模块解析python3
文件。
示例bibtex文件是:
bibtexparser
注意请参阅第2项没有任何@article{ebert2013,
Title={First-principles calculation of the Gilbert damping parameter via the linear response formalism with application to magnetic transition metals and alloys},
Author={Mankovsky, S. and K{\"o}dderitzsch, D. and Woltersdorf, G and Ebert, H.},
Volume={87},
Pages={1},
Year={2013},
Journal={Phys. Rev. B}
}
@article{ebert2011,
title = {\textit{Ab Initio} Calculation of the Gilbert Damping Parameter via the Linear Response Formalism},
author = {Ebert, H. and Mankovsky, S. and K{\"o}dderitzsch, D. and Kelly, P. J.},
journal = {Phys. Rev. Lett.},
volume = {107},
pages = {066603},
month = {Aug},
publisher = {American Physical Society}
}
@article{paudyal2013,
author={Narayan Poudyal and J Ping Liu},
title={Advances in nanostructured permanent magnets research},
journal={Journal of Physics D: Applied Physics},
volume={46},
number={4},
pages={043001},
year={2013}
}
键。
现在,我正在尝试将此文件解析为:
year
因为它没有找到 import bibtexparser
from bibtexparser.bparser import BibTexParser
# from bibtexparser.bwriter import BibTexWriter
from bibtexparser.bibdatabase import BibDatabase
db = BibDatabase()
with open('report.bib') as bibtex_file:
parser = BibTexParser()
db = bibtexparser.load(bibtex_file, parser=parser)
for i in range(0, len(db.entries)):
try:
tuples = (db.entries[i]["title"],db.entries[i]["author"],
db.entries[i]["journal"],db.entries[i]["year"])
except(KeyError):
continue
print(tuples)
条目,所以它一起跳过第二个元素;输出为:
year
但是,所需的行为是获取缺少项目的('First-principles calculation of the Gilbert damping parameter via the linear\nresponse formalism with application to magnetic transition metals and alloys', 'Mankovsky, S. and K{\\"o}dderitzsch, D. and Woltersdorf, G and Ebert, H.', 'Phys. Rev. B', '2013')
('Advances in nanostructured permanent magnets research', 'Narayan Poudyal and J Ping Liu', 'Journal of Physics D: Applied Physics', '2013')
值的条目。
我怎么能这样做?
请帮助。
答案 0 :(得分:3)
使用.get
,您也可以移除try/except
KeyError
db.entries[i].get("year")
使用词典时,通常建议使用dict.get(<key>, default=None)
来阻止 KeyError 例外,同时迭代非清理数据。
另请查看dict.pop(<key>, default)
,它也会阻止例外,但会强制您提供默认值。