3737logger = logging .getLogger (__name__ )
3838
3939
40+ #: Section headings of structured abstracts. PubMed sometimes stores them
41+ #: welded onto the next sentence with no markup at all ("IntroductionThe black
42+ #: widow spider..."), which no tag can mark.
43+ _ABSTRACT_HEADINGS = (
44+ "Abstract|Background|Introduction|Objectives?|Aims?|Purpose|Importance|"
45+ "Context|Design|Setting|Participants|Patients|Methods|Materials and Methods|"
46+ "Interventions?|Measurements|Main Outcome Measures|Results|Findings|"
47+ "Observations|Case Report|Case Presentation|Discussion|Interpretation|"
48+ "Conclusions?|Conclusions and Relevance|Significance|Limitations"
49+ )
50+ _WELDED_HEADING = re .compile (
51+ rf"(?:^|(?<=[.!?])|(?<=: ))[ \t]*({ _ABSTRACT_HEADINGS } )(?=[A-Z])"
52+ )
53+
54+
55+ def _set_off_welded_headings (text : str ) -> str :
56+ """Split a heading welded onto its sentence into a ``"Heading: "`` label.
57+
58+ Only a listed heading, at the start of the text or right after a sentence
59+ ends, and directly followed by a capital letter, so "The Results were"
60+ and "Methodsical" are left alone. A heading right after ": " also counts,
61+ which splits chained headings ("AbstractBackgroundIt" becomes "Abstract:
62+ Background: It") and a welded heading after any earlier label ("Aim:
63+ MethodsWe"). Title-case headings only, on purpose: all-caps welds
64+ ("RESULTSThe") and welds after a bracket ("exposures)Conclusions") are
65+ left as they are.
66+
67+ Examples:
68+ >>> _set_off_welded_headings("IntroductionThe spider. ResultsA total.")
69+ 'Introduction: The spider.\\ n\\ nResults: A total.'
70+ >>> _set_off_welded_headings("The Results were striking.")
71+ 'The Results were striking.'
72+ """
73+
74+ def label (match : re .Match [str ]) -> str :
75+ after_label = text [: match .start ()].endswith (": " )
76+ lead = "" if match .start () == 0 or after_label else "\n \n "
77+ return lead + match .group (1 ) + ": "
78+
79+ # Repeat for chained headings: "AbstractBackgroundIt began." only exposes
80+ # "Background" once "Abstract" has been split off.
81+ while True :
82+ updated = _WELDED_HEADING .sub (label , text )
83+ if updated == text :
84+ return text
85+ text = updated
86+
87+
4088@ReferenceSourceRegistry .register
4189class PMIDSource (ReferenceSource ):
4290 """Fetch references from PubMed using PMID.
@@ -236,7 +284,9 @@ def _render_abstract_sections(element: Any) -> Optional[str]:
236284 """
237285 sections = []
238286 for node in element .find_all ("AbstractText" ):
239- text = node .get_text ().strip ()
287+ # Edits the parsed node in place; nothing reads it again.
288+ PMIDSource ._set_off_inline_headings (node )
289+ text = _set_off_welded_headings (node .get_text ().strip ())
240290 if not text :
241291 continue
242292 label = node .get ("Label" )
@@ -245,6 +295,49 @@ def _render_abstract_sections(element: Any) -> Optional[str]:
245295 joined = "\n \n " .join (sections )
246296 return joined if joined else None
247297
298+ @staticmethod
299+ def _set_off_inline_headings (node : Any ) -> None :
300+ """Turn inline bold section headings into ``"Heading: "`` labels, in place.
301+
302+ Some publishers supply a structured abstract as one ``AbstractText``
303+ whose headings are inline ``<b>``, with no space after them
304+ (``<b>Background</b>Neuroblastoma can arise...``), so ``get_text()``
305+ welds each heading onto the next word and a quote beginning at that
306+ word fails whole-word matching. A ``<b>`` or ``<strong>`` counts as a
307+ heading only at the start of the text or right after a sentence ends,
308+ and only when the text after it starts with a letter; bold inside a
309+ sentence, or not welded to the next word, is left as it is.
310+
311+ Args:
312+ node: An ``AbstractText`` element, modified in place
313+
314+ Examples:
315+ >>> from bs4 import BeautifulSoup
316+ >>> xml = ("<AbstractText><b>Background</b>It began."
317+ ... "<b>Results</b>It worked.</AbstractText>")
318+ >>> node = BeautifulSoup(xml, "xml").find("AbstractText")
319+ >>> PMIDSource._set_off_inline_headings(node)
320+ >>> node.get_text()
321+ 'Background: It began.\\ n\\ nResults: It worked.'
322+ """
323+ for bold in node .find_all (["b" , "strong" ]):
324+ before = "" .join (
325+ str (sibling .get_text () if hasattr (sibling , "get_text" ) else sibling )
326+ for sibling in reversed (list (bold .previous_siblings ))
327+ ).rstrip ()
328+ if before and not before .endswith (("." , "!" , "?" )):
329+ continue
330+ # Only a real weld: the next text starts with a letter, no space.
331+ # "<b>IL</b>-6" and "<b>Importantly</b>," are not headings.
332+ following = bold .next_sibling
333+ if not (isinstance (following , str ) and following [:1 ].isalpha ()):
334+ continue
335+ heading = bold .get_text ().strip ()
336+ if not heading :
337+ continue
338+ label = heading if heading .endswith (":" ) else f"{ heading } :"
339+ bold .replace_with (f"{ chr (10 ) * 2 if before else '' } { label } " )
340+
248341 def _parse_abstract (self , soup : BeautifulSoup ) -> Optional [str ]:
249342 """Parse the abstract from a PubMed article XML document.
250343
0 commit comments