__init__.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """
  2. Generate BibTeX Entries for PubMed Publications
  3. This module utilizes the API of TeXMed,
  4. a BibTeX interface for PubMed.
  5. TeXMed was written by Arne Muller
  6. https://www.bioinformatics.org/texmed/
  7. Command Line Example:
  8. $ pubmed-bibtex 31025164
  9. @Article{pmid31025164,
  10. Author="...",
  11. Title="...",
  12. Journal="...",
  13. ...
  14. }
  15. Python Example:
  16. >>> from pubmed_bibtex import bibtex_entry_from_pmid
  17. >>> print(bibtex_entry_from_pmid(123456789))
  18. Copyright (C) 2019 Fabian Peter Hammerle <fabian@hammerle.me>
  19. This program is free software: you can redistribute it and/or modify
  20. it under the terms of the GNU General Public License as published by
  21. the Free Software Foundation, either version 3 of the License, or
  22. (at your option) any later version.
  23. This program is distributed in the hope that it will be useful,
  24. but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. GNU General Public License for more details.
  27. You should have received a copy of the GNU General Public License
  28. along with this program. If not, see <https://www.gnu.org/licenses/>.
  29. """
  30. import html.parser
  31. import re
  32. import typing
  33. import urllib.parse
  34. import urllib.request
  35. from pubmed_bibtex.version import __version__
  36. __all__ = ["__version__", "bibtex_entry_from_pmid"]
  37. _TEXMED_URL_PATTERN = (
  38. "https://www.bioinformatics.org/texmed/cgi-bin/list.cgi?PMID={pmid}&linkOut"
  39. )
  40. class _TeXMedHtmlParser(html.parser.HTMLParser):
  41. def __init__(self) -> None:
  42. self.bibtex_entry: typing.Optional[str] = None
  43. super().__init__()
  44. @staticmethod
  45. def _strip_bibtex_entry(data: str) -> str:
  46. return re.sub(r"\n\% \d+\s?\n", "", data).strip() + "\n"
  47. def handle_data(self, data: str) -> None:
  48. if "Author" in data:
  49. self.bibtex_entry = self._strip_bibtex_entry(data)
  50. @staticmethod
  51. def error(message: str) -> None:
  52. raise Exception(message) # pragma: no cover
  53. def bibtex_entry_from_pmid(pmid: str) -> typing.Optional[str]:
  54. assert pmid.isdigit(), pmid
  55. parser = _TeXMedHtmlParser()
  56. with urllib.request.urlopen( # raises urllib.error.HTTPError
  57. _TEXMED_URL_PATTERN.format(pmid=urllib.parse.quote(pmid))
  58. ) as resp:
  59. parser.feed(resp.read().decode("utf-8"))
  60. return parser.bibtex_entry