Skip to main content
 首页 » 编程设计

python之使用 Python 解析 BibTeX 引文格式

2025年05月04日13kerrycode

在 python 中解析这些结果的最佳方法是什么?我试过正则表达式但无法正常工作。我正在寻找标题、作者等作为键的字典。

@article{perry2000epidemiological, 
  title={An epidemiological study to establish the prevalence of urinary symptoms and felt need in the community: the Leicestershire MRC Incontinence Study}, 
  author={Perry, Sarah and Shaw, Christine and Assassa, Philip and Dallosso, Helen and Williams, Kate and Brittain, Katherine R and Mensah, Fiona and Smith, Nigel and Clarke, Michael and Jagger, Carol and others}, 
  journal={Journal of public health}, 
  volume={22}, 
  number={3}, 
  pages={427--434}, 
  year={2000}, 
  publisher={Oxford University Press} 
} 

请您参考如下方法:

这看起来像是一种引用格式。你可以这样解析它:

>>> import re 
 
>>> kv = re.compile(r'\b(?P<key>\w+)={(?P<value>[^}]+)}') 
 
>>> citation = """ 
... @article{perry2000epidemiological, 
...   title={An epidemiological study to establish the prevalence of urinary symptoms and felt need in the community: the Leicestershire MRC Incontinence 
...  Study}, 
...   author={Perry, Sarah and Shaw, Christine and Assassa, Philip and Dallosso, Helen and Williams, Kate and Brittain, Katherine R and Mensah, Fiona and 
...  Smith, Nigel and Clarke, Michael and Jagger, Carol and others}, 
...   journal={Journal of public health}, 
...   volume={22}, 
...   number={3}, 
...   pages={427--434}, 
...   year={2000}, 
...   publisher={Oxford University Press} 
... } 
... """ 
 
>>> dict(kv.findall(citation)) 
{'author': 'Perry, Sarah and Shaw, Christine and Assassa, Philip and Dallosso, Helen and Williams, Kate and Brittain, Katherine R and Mensah, Fiona and Smith, Nigel and Clarke, Michael and Jagger, Carol and others', 
 'journal': 'Journal of public health', 
 'number': '3', 
 'pages': '427--434', 
 'publisher': 'Oxford University Press', 
 'title': 'An epidemiological study to establish the prevalence of urinary symptoms and felt need in the community: the Leicestershire MRC Incontinence Study', 
 'volume': '22', 
 'year': '2000'} 

正则表达式使用两个命名的捕获组(主要是为了直观地表示什么是什么)。

  • “key”是任何 1+ unicode 单词字符,左边是单词边界,右边是文字等号;
  • “值”是两个大括号内的内容。只要您不希望有“嵌套”大括号,就可以方便地使用 [^}]。换句话说,这些值只是大括号内不是大括号的任何字符中的一个或多个。