File size: 5,650 Bytes
266eda8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | """
Citation Parser for Literature Data Entry
- Auto-extract fields from pasted citations
- Generate source labels
- Support for multiple citation formats (APA, MLA, Chicago, Vancouver)
"""
import re
from typing import Dict, Optional
def parse_citation(citation: str) -> Dict[str, Optional[str]]:
"""
Auto-extract fields from pasted citation.
Handles common formats:
- "Smith J, Jones K. (2023). Title of paper. Journal Name. DOI: 10.1234/journal.2023.001"
- "Smith et al. Title of paper. Journal. 2023. https://doi.org/10.1234/..."
- APA, MLA, Chicago, Vancouver styles
Returns:
dict with keys: first_author, publication_year, paper_title, doi, journal, source_label
"""
result = {
"first_author": None,
"publication_year": None,
"paper_title": None,
"doi": None,
"journal": None,
"source_label": None
}
if not citation or not citation.strip():
return result
# Clean citation
citation = citation.strip()
# Extract DOI (multiple patterns)
doi_patterns = [
r'(?:doi:|DOI:)\s*(10\.\d{4,}/[^\s]+)', # doi: 10.1234/...
r'https?://doi\.org/(10\.\d{4,}/[^\s]+)', # https://doi.org/10.1234/...
r'(10\.\d{4,}/[^\s,]+)', # bare DOI
]
for pattern in doi_patterns:
match = re.search(pattern, citation, re.IGNORECASE)
if match:
result["doi"] = match.group(1).rstrip('.,;)')
break
# Extract year (4-digit number, typically in parens or after comma)
year_patterns = [
r'\((\d{4})\)', # (2023)
r'\s(\d{4})[.,;\s]', # 2023. or 2023,
r'\s(\d{4})$', # 2023 at end
]
for pattern in year_patterns:
match = re.search(pattern, citation)
if match:
year = int(match.group(1))
if 1950 <= year <= 2035:
result["publication_year"] = year
break
# Extract first author (before first comma or "et al")
# Handles: "Smith J," "Smith," "Smith et al."
author_patterns = [
r'^([A-Z][a-zA-Z\'\-]+)(?:\s+[A-Z]\.?)?[\s,]', # Smith J, or Smith,
r'^([A-Z][a-zA-Z\'\-]+)\s+et\s+al', # Smith et al
r'^([A-Z][a-zA-Z\'\-]+)', # Just "Smith"
]
for pattern in author_patterns:
match = re.match(pattern, citation)
if match:
result["first_author"] = match.group(1)
break
# Try to extract title (between year and journal, or in quotes)
# Pattern: After year/author, before journal/DOI
title_patterns = [
r'\.\s*([A-Z][^\.]+)\.\s+[A-Z][a-z]+', # Title between periods
r'[""]([^""]+)[""]', # In quotes
r'\(\d{4}\)\.\s*([^\.]+)\.', # After (year).
r',\s*([A-Z][^,\.]+)[,\.]', # After comma (some formats)
]
for pattern in title_patterns:
match = re.search(pattern, citation)
if match:
title = match.group(1).strip()
# Reasonable title length and doesn't look like a journal name
if 10 < len(title) < 300 and not re.match(r'^[A-Z][a-z]+$', title):
result["paper_title"] = title
break
# Try to extract journal (often italicized or after title)
# Look for pattern: Title. JournalName. or Title. JournalName, Year
journal_patterns = [
r'\.\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+){0,4})[,\.]?\s+\d{4}', # Before year
r'\.\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+){0,4})\.', # Between periods
]
for pattern in journal_patterns:
match = re.search(pattern, citation)
if match:
journal = match.group(1).strip()
# Make sure it's not the title (titles are usually longer)
if len(journal) < 50:
result["journal"] = journal
break
# Auto-generate source_label: "Smith2023" or "Smith_2023_Biomaterials"
if result["first_author"] and result["publication_year"]:
source_label = f"{result['first_author']}{result['publication_year']}"
if result["journal"]:
# Add journal abbreviation (first word, max 10 chars)
journal_abbr = result["journal"].split()[0][:10]
source_label = f"{result['first_author']}_{result['publication_year']}_{journal_abbr}"
result["source_label"] = source_label
return result
# Example usage and test cases
if __name__ == "__main__":
test_citations = [
# APA format
"Smith, J., & Jones, K. (2023). Decellularized mammary ECM promotes organoid formation. Biomaterials, 45(3), 123-134. doi: 10.1016/j.biomaterials.2023.001",
# Nature format
"Smith, J. et al. Decellularized mammary ECM promotes organoid formation. Nature 612, 123-130 (2023). https://doi.org/10.1038/s41586-023-12345-6",
# Short format
"Smith et al. (2023). Decellularized ECM for organoids. Biomaterials. 10.1016/j.biomaterials.2023.001",
# Vancouver
"Smith J, Jones K, Brown M. Decellularized mammary ECM. Biomaterials. 2023;45:123-134.",
# With URL
"Smith J. Decellularized mammary ECM. Biomaterials, 2023. https://doi.org/10.1016/j.biomaterials.2023.001",
]
print("Testing Citation Parser:\n")
for i, citation in enumerate(test_citations, 1):
print(f"Test {i}:")
print(f"Input: {citation[:80]}...")
result = parse_citation(citation)
print(f"Parsed:")
for key, value in result.items():
if value:
print(f" {key}: {value}")
print()
|