2016-01-17 82 views
0

我想解析一個bibtex文件與python3bibtexparser模塊。缺少條目的python元組

樣本中文提供的文件是:

@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} 
} 

注意見第2項沒有任何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') 

但是,期望的行爲是獲得與丟失物品的NULL值的條目。

我該怎麼做?

我其實已經通過thisthis等問題,但沒有得到太多。

請幫忙。

+0

難道你不只是迭代db.entries,而不是使用範圍+ len ....我....?如果是的話,它會更清潔;-)在db.entries中輸入:... entry.get('title'),entry.get('author'),entry.get('journal'),entry.get ('年') –

回答

3

使用.get,你可以刪除try/exceptKeyError異常以及

db.entries[i].get("year") 

藉助詞典,它經常被建議使用dict.get(<key>, default=None),防止KeyError異常例外,而在非迭代數據清理

也看看dict.pop(<key>, default),它也可以防止異常但強制您提供默認值。