¿Cuál es la mejor manera en python para analizar estos resultados? He intentado regex pero no puedo hacer que funcione. Estoy buscando un diccionario de título, autor, etc. como claves.

@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}
}
1
gmoorevt 5 mar. 2018 a las 00:27

4 respuestas

La mejor respuesta

Es posible que esté buscando un BibTeX -parser: https://bibtexparser.readthedocs.io/en/master/

Fuente: https://bibtexparser.readthedocs.io/en/ master / tutorial.html # step-0-vocabulary

Entrada / Crear archivo bibtex:

bibtex = """@ARTICLE{Cesar2013,
  author = {Jean César},
  title = {An amazing title},
  year = {2013},
  month = jan,
  volume = {12},
  pages = {12--23},
  journal = {Nice Journal},
  abstract = {This is an abstract. This line should be long enough to test
     multilines...},
  comments = {A comment},
  keywords = {keyword1, keyword2}
}
"""

with open('bibtex.bib', 'w') as bibfile:
    bibfile.write(bibtex)

Analízalo:

import bibtexparser

with open('bibtex.bib') as bibtex_file:
    bib_database = bibtexparser.load(bibtex_file)

print(bib_database.entries)

Salida:

[{'journal': 'Nice Journal',
  'comments': 'A comment',
  'pages': '12--23',
  'month': 'jan',
  'abstract': 'This is an abstract. This line should be long enough to test\nmultilines...',
  'title': 'An amazing title',
  'year': '2013',
  'volume': '12',
  'ID': 'Cesar2013',
  'author': 'Jean César',
  'keyword': 'keyword1, keyword2',
  'ENTRYTYPE': 'article'}]
2
Patrick Artner 4 mar. 2018 a las 21:53

Puedes usar regex:

import re

s = """
  @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}
}
"""
results = re.findall('(?<=@article\{)[a-zA-Z0-9]+|(?<=\=\{)[a-zA-Z0-9:\s,]+|[a-zA-Z]+(?=\=)|@[a-zA-Z0-9]+', s)
final_results = {results[i][1:] if results[i].startswith('@') else results[i]:int(results[i+1]) if results[i+1].isdigit() else results[i+1] for i in range(0, len(results), 2)}

Salida:

{'publisher': 'Oxford University Press', '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', 'title': 'An epidemiological study to establish the prevalence of urinary symptoms and felt need in the community: the Leicestershire MRC Incontinence Study', 'number': 3, 'volume': 22, 'year': 2000, 'article': 'perry2000epidemiological', 'pages': 427}
1
Ajax1234 4 mar. 2018 a las 21:36

Esto parece un formato de cita. Podrías analizarlo así:

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

La expresión regular utiliza dos grupos de captura con nombre (principalmente solo para denotar visualmente qué es qué).

  • "clave" es cualquier carácter de palabra unicode 1+, con un límite de palabra a la izquierda y un signo igual literal a su derecha;
  • "valor" es algo dentro de dos llaves. Puede usar [^}] convenientemente siempre que no espere tener llaves "anidadas". En otras palabras, los valores son solo uno o más de los caracteres que no son llaves, dentro de las llaves.
5
Brad Solomon 4 mar. 2018 a las 21:38

Quizás esté buscando re.split:

import re
article_dict = {}
with open('inp.txt') as f:
    for line in f.readlines()[1:-1]:
        info = re.split(r'=',line.strip())
        article_dict[info[0]] = info[1]

Supongo que tendrá que deshacerse de los corchetes y las comas al final, que es solo una simple tarea de reemplazar o rebanar.

{'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}'}
1
Patrick Artner 4 mar. 2018 a las 21:50