Skip to content

Instantly share code, notes, and snippets.

@dobrosketchkun
Last active February 18, 2024 14:20
Show Gist options
  • Save dobrosketchkun/f14e1ab9ae817b00b28251f11786fbcf to your computer and use it in GitHub Desktop.
Save dobrosketchkun/f14e1ab9ae817b00b28251f11786fbcf to your computer and use it in GitHub Desktop.
DOI to citation
#!/usr/bin/env python
#http://www.crosscite.org/cn/
import requests
import json
class CrossRefClient(object):
def __init__(self, accept='text/x-bibliography; style=apa', timeout=3):
"""
# Defaults to APA biblio style
# Usage:
s = CrossRefClient()
print s.doi2apa("10.1038/nature10414")
"""
self.headers = {'accept': accept}
self.timeout = timeout
def query(self, doi, q={}):
if doi.startswith("http://"):
url = doi
else:
url = "http://dx.doi.org/" + doi
r = requests.get(url, headers = self.headers)
return r
def doi2apa(self, doi):
self.headers['accept'] = 'text/x-bibliography; style=apa'
return self.query(doi).text
def doi2turtle(self, doi):
self.headers['accept'] = 'text/turtle'
return self.query(doi).text
def doi2json(self, doi):
self.headers['accept'] = 'application/vnd.citationstyles.csl+json'
return self.query(doi).json()
# keys = ['indexed', 'reference-count', 'publisher', 'issue', 'funder', 'content-domain', 'published-print', 'DOI', 'type', 'created', 'update-policy', 'source', 'is-referenced-by-count', 'title', 'prefix', 'volume', 'author', 'member', 'published-online', 'reference', 'container-title', 'original-title', 'language', 'link', 'deposited', 'score', 'subtitle', 'short-title', 'issued', 'references-count', 'journal-issue', 'alternative-id', 'URL', 'relation', 'ISSN', 'container-title-short', 'article-number']
doi = '10.1186/s13059-015-0796-9'
session = CrossRefClient()
out = session.doi2json(doi)
def names(ref):
name = []
for _item in ref['author']:
given_in = _item['given'].split(' ')
given = ''.join([_name[0] + '.' for _name in given_in])
name.append(_item['family'] + ', ' + given +', ')
return ''.join(name[0:-1]) + 'and ' + name[-1][0:-2]
authors = names(out)
year = str(out['created']['date-parts'][0][0])
title = out['title']
journal_short = out['container-title-short']
volume = str(out['volume'])
pages = str(out['article-number'])
DOI = out['DOI']
ref = authors + ' ' + year + '. ' + title + '. ' + journal_short + '. ' + volume + ':' + pages + ' doi:/' + DOI
print(ref)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment