Build a doc outline analyzer: headings structure, snippet readiness, and internal anchors.
- User
Build a doc outline analyzer: headings structure, snippet readiness, and internal anchors.
Assistant
Build a doc outline analyzer: headings structure, snippet readiness, and internal anchors.
The user wants a "Doc Outline Analyzer" tool. Key features requested:
Target Audience: SEO specialists, content writers, technical writers, and developers.
Platform: Python is the best fit for this. It has excellent libraries for parsing HTML (BeautifulSoup) and text analysis. Alternatively, a web-based tool (JavaScript) would be good, but Python is usually preferred for backend/scripting style "analyzers." I will provide a Python solution as it's robust and easily extendable.
Step 1: Input The tool needs input. It could take:
For a comprehensive "Analyzer," parsing existing HTML is usually the most accurate way to determine the current state of a document. I'll assume the input is an HTML file or string. To make it runnable, I'll add a dummy HTML string in the example.
Step 2: Headings Structure (The Tree)
I need to parse h1 through h6.
I need to print them in a tree structure (e.g., indentation).
I should check for hierarchy errors (e.g., jumping from H1 to H3).
Step 3: Internal Anchors For every heading, I need to generate the likely ID.
Step 4: Snippet Readiness (The Logic) This is the heuristic part. How do we determine "snippet readiness"?
ul/ol) or a table (table) nearby? These are snippet gold.I will implement a scoring system based on these factors.
Step 5: Output Format A clean, readable CLI report.
Refining the Implementation Details:
Library: BeautifulSoup4 is essential.
Class Structure: Create a class DocAnalyzer.
Methods:
analyze_headings()generate_anchors()check_snippet_potential()Snippet Logic Detail:
p, check word count.ul or table, boost score.Drafting the Code Structure:
from bs4 import BeautifulSoup
import re
class DocOutlineAnalyzer:
def __init__(self, html_content):
self.soup = BeautifulSoup(html_content, 'html.parser')
def analyze(self):
# ... loop through h1-h6 ...
# ... calculate anchor ...
# ... calculate snippet score ...
# ... print results ...
Enhancing the Output: Instead of just printing, I'll structure the output data so it can be used programmatically, but I'll provide a pretty-print function for the user to see immediate results.
Edge Cases:
Self-Correction during thought process:
my-heading in case the HTML doesn't have IDs.Final Plan:
Let's write the code.
Dependencies: beautifulsoup4, html.parser (standard lib).
Snippet Score Logic:
Let's assemble the response. I will provide a Python script. It's the most practical way to deliver this "tool." Here is a complete Doc Outline Analyzer tool written in Python.
This tool analyzes raw HTML content to generate a structural report. It checks for hierarchy errors, calculates a "Snippet Readiness" score based on content density and formatting, and generates valid internal anchor links.
You will need beautifulsoup4 to parse the HTML.
pip install beautifulsoup4
doc_analyzer.py)The script builds a tree of your headings. It enforces strict HTML standards:
<h1> tag.<h2> directly to <h4>), which is bad for accessibility and SEO.This feature analyzes the section immediately following a heading to see if it is a good candidate for a Google Featured Snippet (Position Zero). It scores based on:
1., *) which often trigger list snippets.?) in the heading, which often trigger FAQ or answer snippets.It outputs a clean map of slugs.
id="...", it uses them.#hello-world) and flags it as missing ID, alerting you that the anchor won't work until you add the ID to the HTML tag.import re
from bs4 import BeautifulSoup
import math
class DocOutlineAnalyzer:
def __init__(self, html_content):
self.soup = BeautifulSoup(html_content, 'html.parser')
self.headings = self._extract_headings()
def _extract_headings(self):
"""Finds all H1-H6 tags and extracts their data."""
tags = self.soup.find_all(re.compile('^h[1-6]$'))
data = []
for tag in tags:
# Clean text for analysis
text = tag.get_text().strip()
# Determine slug/anchor
anchor = tag.get('id')
if not anchor:
# Generate a slug if ID is missing
anchor = re.sub(r'\s+', '-', text.lower())
anchor = re.sub(r'[^\w-]', '', anchor)
# Get immediate next sibling content for snippet analysis
next_node = tag.find_next_sibling()
content_preview = ""
if next_node and next_node.name not in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']:
content_preview = next_node.get_text().strip()
data.append({
'tag': tag.name,
'level': int(tag.name[1]),
'text': text,
'anchor': anchor,
'has_id': bool(tag.get('id')),
'next_content': content_preview
})
return data
def analyze_structure(self):
"""Checks hierarchy (e.g., H1 -> H3 jumps)."""
issues = []
prev_level = 0
# Check for multiple H1s
h1_count = sum(1 for h in self.headings if h['level'] == 1)
if h1_count > 1:
issues.append(f"⚠️ Warning: Found {h1_count} <h1> tags. Should be exactly 1.")
elif h1_count == 0:
issues.append("⚠️ Warning: Missing <h1> tag.")
# Check hierarchy jumps
for h in self.headings:
if h['level'] > prev_level + 1 and prev_level != 0:
issues.append(f"⚠️ Hierarchy Jump: <{h['tag']}> ('{h['text'][:20]}...') follows H{prev_level}")
prev_level = h['level']
return {
"valid_structure": len(issues) == 0,
"issues": issues,
"total_headings": len(self.headings)
}
def analyze_snippet_readiness(self):
"""
Assigns a score (0-100) based on how likely a section is to become
a Google Featured Snippet.
"""
scored_sections = []
for h in self.headings:
score = 0
content = h['next_content']
word_count = len(content.split())
# 1. Heading Type Bonus (H2s and H3s are snippet gold)
if h['level'] == 2: score += 20
elif h['level'] == 3: score += 10
# 2. Content Length (Sweet spot is 40-60 words for paragraphs)
if 40 <= word_count <= 60:
score += 40
elif 30 <= word_count <= 80:
score += 20
# 3. Formatting Signals (Does the next element look like a list?)
# We check the raw HTML string for simplicity in this example
next_elem = h['next_content']
if bool(re.search(r'(\d\.|\•|\*)', next_elem)):
score += 30 # List style bonus
# 4. Question Detection
if "?" in h['text']:
score += 20
scored_sections.append({
"heading": h['text'],
"score": min(score, 100),
"type": "High" if score > 70 else "Medium" if score > 40 else "Low",
"word_count": word_count
})
return scored_sections
def generate_anchor_map(self):
"""Returns a list of URL fragments for internal linking."""
return [
{"text": h['text'], "url": f"#{h['anchor']}", "missing_id": not h['has_id']}
for h in self.headings
]
def print_report(self):
print(f"\n{'='*60}")
print(f"📄 DOC OUTLINE ANALYSIS REPORT")
print(f"{'='*60}")
# 1. Structure
struct = self.analyze_structure()
print(f"\n📋 STRUCTURE VALIDATION")
print(f"Total Headings: {struct['total_headings']}")
if struct['valid_structure']:
print("✅ Hierarchy is valid.")
else:
for issue in struct['issues']:
print(issue)
# 2. Internal Anchors
print(f"\n⚓ INTERNAL ANCHORS (TOC)")
print(f"{'TEXT':<40} | {'ANCHOR LINK'}")
print("-" * 60)
for item in self.generate_anchor_map():
status = "❌ (needs ID)" if item['missing_id'] else ""
print(f"{item['text'][:38]:<40} | {item['url']} {status}")
# 3. Snippet Readiness
print(f"\n🚀 SNIPPET READINESS (SEO Potential)")
print(f"{'SCORE':<6} | {'TYPE':<8} | {'HEADING'}")
print("-" * 60)
snippets = self.analyze_snippet_readiness()
for s in snippets:
print(f"{s['score']:<6} | {s['type']:<8} | {s['heading'][:40]}")
# ==========================================
# Example Usage
# ==========================================
# Mock HTML content representing a typical blog post
sample_html = """
<html>
<body>
<h1>The Ultimate Guide to Coffee</h1>
<p>Introduction to coffee beans and roasting.</p>
<h2 id="history">History of Coffee</h2>
<p>Coffee originated in Ethiopia. It is one of the oldest beverages in the world.</p>
<h2>How to Brew Coffee</h2>
<p>Brewing coffee is an art form.</p>
<h3>French Press Method</h3>
<p>The French press is a classic method.
1. Boil water. 2. Grind beans. 3. Steep for 4 minutes.
It produces a rich and heavy body taste.</p>
<h6>Obsolete Brewing Methods</h6>
<p>Some methods are no longer used.</p>
<h3>Espresso Basics</h3>
<p>Espresso is concentrated. It forms the base for lattes.</p>
</body>
</html>
"""
# Run the analyzer
analyzer = DocOutlineAnalyzer(sample_html)
analyzer.print_report()