Python guide
How to Parse a Resume in Python
This guide shows how to get data out of PDF and DOCX resumes with Python: first the do-it-yourself route with open-source libraries, then the API route that returns structured JSON. Every snippet below was run against a real file, and the outputs shown are what it printed. Also available for Node.js and PHP.
What you need
- Python 3.9 or newer
pip install pdfplumber python-docx requests- A sample resume (PDF or DOCX)
1Extract the text from PDF and DOCX files
Resumes arrive as PDF or Word files, so the first job is getting plain text out of them. pdfplumber reads text-based PDFs page by page and python-docx reads the paragraphs of a DOCX file.
import pdfplumber
from docx import Document
def extract_text(path: str) -> str:
"""Return the plain text of a PDF or DOCX resume."""
if path.lower().endswith(".pdf"):
with pdfplumber.open(path) as pdf:
return "\n".join(page.extract_text() or "" for page in pdf.pages)
if path.lower().endswith(".docx"):
return "\n".join(p.text for p in Document(path).paragraphs)
raise ValueError(f"Unsupported file type: {path}")
text = extract_text("resume.pdf")
print(text[:300])Output:
Maria Lopez
Senior Backend Engineer
San Francisco, CA | [email protected] | +1 415 555 0142
linkedin.com/in/marialopez-example | github.com/marialopez-example
SUMMARY
Backend engineer with 7 years of experience building Python and Go services on A
WS.Notice the last line: the PDF wrapped "AWS" across two lines, so the raw text says A / WS. Line breaks, columns and headers put in the wrong order are the everyday problems of PDF text extraction. DOCX files are cleaner because paragraphs are stored as text, not positioned on a page.
2Pull out contact details with regular expressions
Some fields have a predictable shape, so a regular expression finds them reliably:
import re
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
PHONE = re.compile(r"\+?\d[\d\s().-]{7,}\d")
LINKEDIN = re.compile(r"linkedin\.com/in/[\w-]+", re.I)
def extract_contact(text: str) -> dict:
email = EMAIL.search(text)
phone = PHONE.search(text)
linkedin = LINKEDIN.search(text)
return {
"email": email.group() if email else None,
"phone": phone.group().strip() if phone else None,
"linkedin": linkedin.group() if linkedin else None,
}
print(extract_contact(text)){'email': '[email protected]', 'phone': '+1 415 555 0142', 'linkedin': 'linkedin.com/in/marialopez-example'}This is where the simple approach stops working. Job titles, employers, dates, degrees and skills have no fixed format. Every candidate orders sections differently, writes dates differently ("Mar 2021", "03/2021", "2021-present"), and uses different headings. Writing rules for all of that is a project of its own; we cover the options in how to build a resume parser.
3Get structured JSON from a resume parser API
If you need the full structure (work history, education, skills, certifications), a resume parser API does the hard part. The example uses the CV Parser Pro resume parser API. Create a free account to get an API key (10 free parses, no credit card), then set it as an environment variable:
export CVPP_API_KEY="ts_your_api_key"Parsing is asynchronous: you upload the file, get an id back immediately, and poll until the result is ready. This function wraps that in one call:
import os
import time
import requests
API = "https://cvparserpro.com/api/v1"
HEADERS = {"X-API-Key": os.environ["CVPP_API_KEY"]}
def parse_resume(path: str, timeout: int = 120) -> dict:
"""Upload a resume and wait for the structured result."""
with open(path, "rb") as f:
upload = requests.post(f"{API}/parse", headers=HEADERS, files={"files": f})
upload.raise_for_status()
candidate_id = upload.json()["candidates"][0]["id"]
deadline = time.time() + timeout
while time.time() < deadline:
resp = requests.get(f"{API}/candidates/{candidate_id}", headers=HEADERS)
resp.raise_for_status()
data = resp.json()["data"]
if data["parsing_status"] == "completed":
return data
if data["parsing_status"] == "failed":
raise RuntimeError(data["parsing_errors"])
time.sleep(3)
raise TimeoutError(f"Resume {candidate_id} was not parsed within {timeout}s")
resume = parse_resume("resume.pdf")
print(resume["full_name"], "-", resume["current_title"])
for job in resume["work_history"]:
print(f'{job["start_date"]} to {job["end_date"]}: {job["title"]} at {job["company"]}')Maria Lopez - Senior Backend Engineer
2021-03 to present: Senior Backend Engineer at Northwind Logistics
2018-01 to 2021-02: Software Engineer at Brightline HealthThe same fictional resume came back with its two jobs, dates normalised to YYYY-MM, and "AWS" read correctly despite the broken line in the PDF. In this run it took about 9 seconds. The full response also includes education, certifications, skills, spoken languages, a short summary and a confidence score for each field. See the API reference for every field.
4Parse a folder of resumes into a CSV
Put your files in a resumes/ folder and reuse parse_resume to build a spreadsheet of candidates:
import csv
from pathlib import Path
rows = []
for path in sorted(Path("resumes").glob("*.*")):
if path.suffix.lower() not in (".pdf", ".docx"):
continue
try:
r = parse_resume(str(path))
rows.append({
"file": path.name,
"name": r["full_name"],
"email": r["email"],
"title": r["current_title"],
"years": r["years_of_experience"],
"skills": ", ".join(r["skills"] or []),
})
except Exception as e:
print(f"{path.name}: {e}")
with open("candidates.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["file", "name", "email", "title", "years", "skills"])
writer.writeheader()
writer.writerows(rows)
print(f"Saved {len(rows)} candidates to candidates.csv")file,name,email,title,years,skills
maria.docx,Maria Lopez,[email protected],Senior Backend Engineer,7,"Python, Go, PostgreSQL, Kubernetes, AWS, Apache Kafka, Docker"
maria.pdf,Maria Lopez,[email protected],Senior Backend Engineer,7,"Python, Go, PostgreSQL, Kubernetes, AWS, Apache Kafka, Docker"Files that fail (for example a scanned PDF with no text layer) are reported and skipped, and their credit is refunded. For large volumes you can also send several files in one upload request; each file gets its own candidate id.
Which approach should you use?
| Libraries + regex | Resume parser API | |
|---|---|---|
| Contact details | Yes | Yes |
| Work history, education | Hard, layout-dependent | Yes, as JSON |
| Cost | Free (your time) | 10 free, then $0.02 to $0.06 per resume |
| Data leaves your servers | No | Yes |
| Scanned PDFs | Needs OCR | Not supported |