Build a Semantic Keyword Clustering System with Python in Claude Code
Semantic keyword clustering groups search phrases by what they mean rather than by the words they share, so that every group can become one page. A working system has four parts with four separate jobs: Python runs the process, an embedding model turns each keyword into numbers that stand for its meaning, a clustering algorithm groups the numbers that sit close together, and Claude Code helps you write, test and maintain the Python. A person then reviews the groups, because meaning and search intent are not the same thing. This guide builds that system one step at a time, from a messy keyword export to a cluster table you can publish from.
Five steps from a keyword export to a page map
- 01Cleanone row per distinct phrase, noise removed
- 02Embedone model turns each phrase into numbers
- 03Comparecosine similarity scores every pair
- 04Clusterthe algorithm groups the close ones
- 05Reviewa person splits, merges and approves
- What is semantic keyword clustering?
- Why use Python for semantic clustering?
- What role does Claude Code play?
- Text embeddings, in simple terms
- Preparing and cleaning a keyword dataset
- Generating keyword embeddings
- Measuring similarity between keywords with cosine similarity
- Applying a keyword clustering algorithm
- Building the system with Claude Code: a worked example
- Reviewing and correcting inaccurate clusters
- How to export keyword clusters into an SEO structure
- Limitations of semantic keyword clustering, and what it costs to run
- Frequently asked questions
- Where to start
What is semantic keyword clustering?
Semantic keyword clustering is the practice of grouping search phrases by meaning, so that phrases asking the same thing in different words land in one group and can be answered by one page. "Patio paving ideas" and "ideas for a paved terrace" share almost no words, yet a reader typing either wants the same article. A word-matching method keeps them apart; a semantic method compares what they mean and puts them together. Each group it produces is a candidate for one page.
A keyword list on its own is not a plan. A few hundred phrases hide a few dozen real questions, and without grouping, the same question gets written up two or three times under slightly different titles. Google's own SEO Starter Guide says its systems can understand how a page relates to many queries even when the page never uses their exact terms, so the target is one strong page per question, not one page per phrase.
The other honest way to group keywords compares the search results each phrase returns; our guide to automating keyword clustering from a list to a content cluster sets the two side by side. This post goes underneath the semantic method: the code, the numbers it produces, and where it goes wrong.
Why use Python for semantic clustering?
Python is the right language for semantic clustering because the three pieces the job needs, an embedding model, a similarity calculation and a clustering algorithm, all have mature, free libraries in Python that pass data to each other in the same array format. You write none of the mathematics, only the glue between them.
Two open libraries carry most of the weight. Sentence Transformers loads open embedding models and turns a list of phrases into vectors in one call, and its documentation includes worked clustering examples for k-means, agglomerative clustering and a faster community-detection method. scikit-learn supplies the clustering algorithms themselves, with the same interface for each, so trying a second algorithm is a one-line change rather than a rewrite.
Python also keeps the method yours: a paid tool hides its settings, while a script is a few files you can read, change and rerun, and it can show the number that put two phrases together.
What role does Claude Code play?
Claude Code helps you write, change, test and maintain the Python application; it does not do the clustering. The grouping is done by the embedding model and the clustering algorithm, inside a Python process running on your machine. Anthropic describes Claude Code as an agentic coding tool that reads your codebase, edits files and runs commands, and that is exactly the job here: it is the developer sitting beside you, not the engine.
From Claude Code to the reviewer, one owner per stage
- 01Claude Codebuildwrites, tests and maintains the Python
- 02Pythonrunmoves the file from cleaning to export
- 03Embedding modelencodeturns each keyword into numbers for its meaning
- 04The algorithmgroupputs the close representations together
- 05A personapprovecorrects the wrong groups and approves the map
Keeping the roles apart is what makes the system trustworthy. A language model grouping a list by reading it can give two answers on two runs, and nobody can say why; it is the same gap our comparison of a Content OS and ChatGPT describes, a tool that writes but holds no standard. A script gives the same groups from the same input and settings every time, and Claude Code's work is checked like any other code: by reading it and running its tests.
| Part | Its one job | What it does not do |
|---|---|---|
| Claude Code | Helps write, modify, test and maintain the Python application | Group keywords, or decide which phrases belong together |
| Python | Runs the clustering process from file in to file out | Understand meaning; it moves data between the parts |
| Embedding model | Converts each keyword into a list of numbers that represents its meaning | Know your business, your pages or what a searcher intends to buy |
| Clustering algorithm | Groups the numerical representations that sit close together | Name the groups, or judge whether a group deserves a page |
| A person | Reviews the groups, corrects the wrong ones and approves the map | Recompute similarity by hand; the script already did |
The same division of labour holds when Claude Code builds a whole content system: our guide to content automation in Claude Code shows it researching, drafting and checking while a person approves.
Text embeddings, in simple terms
A text embedding is a list of numbers that stands for what a piece of text means, produced so that texts with similar meanings get similar lists. Picture a map where every phrase is a pin, and the distance between two pins tells you how related they are. Google's machine learning course on embedding space puts it the same way: things used in similar contexts end up closer together, and the distance between two items can be read as a measure of how similar they are.
A real model's map has far more than two directions. According to its model card for all-MiniLM-L6-v2, that open model turns each sentence into 384 numbers. You never read them; you only ask how close one phrase is to another.
Sentence embeddings of this kind became practical with Sentence-BERT in 2019. Its paper on sentence embeddings using Siamese BERT networks describes embeddings compared with cosine similarity and reports that finding the most similar pair in a collection dropped from 65 hours with the earlier approach to about 5 seconds. That is why clustering a keyword list on a laptop is ordinary today.
The thing to hold on to: an embedding captures how language is used, not what your customer intends. "Garden room planning permission" and "garden room ideas" sit near each other on the map, though one reader wants a legal answer and the other wants pictures. That comes back in the review step.
Preparing and cleaning a keyword dataset
Cleaning a keyword dataset means reducing the export to one row per distinct phrase, noise removed and useful columns kept, before any embedding is made. Most bad clusters start here: duplicates and stray spellings give the model several pins for one idea, and the algorithm builds a group out of the copies.
What survives the cleaning script
- Every row in both exports combine, keep the source
- Rows with plain text normalise case and quotes
- Rows without duplicates merge plurals and order
- Rows you will write apply the drop rules
- One row per distinct phrase what gets embedded
Start from your own data. Search Console's Performance report shows the queries that already bring people to your site, with clicks and impressions, and its export button downloads the table. Add any research-tool export, keep a source column, and let the cleaning script apply a fixed order of rules. If you want a reading of that Search Console table before writing any code, our prompts for SEO content include one for Search Console data and one that sketches a topic cluster from a single keyword. The rules:
- Normalise the text. Lower-case, trim spaces, straighten quotes and dashes, so "Patio Ideas " and "patio ideas" become one row.
- Merge duplicates and near-duplicates. Plurals and word order ("garden room cost", "cost of a garden room") merge before embedding, keeping the version with the most impressions.
- Separate branded phrases. Your own brand and other companies' names pull phrases together for the wrong reason, so move them to their own list.
- Drop what you will never write about. Jobs, free downloads, places you do not serve: write the rule once and let the script apply it.
- Keep the numbers. Impressions, clicks and the source travel with each phrase, because the review step needs them later.
Each rule is a small function with a test built from real examples on your list. That is the first place Claude Code earns its keep: you describe the rule, it writes the function and the test, and you read both.
Generating keyword embeddings
Generating keyword embeddings means sending every cleaned phrase through one embedding model and storing the vector beside the phrase, so the rest of the pipeline never calls the model again. The choice that matters is the model: an open one on your own machine, or a hosted one over an API.
Two routes to keyword embeddings
A hosted model
- called over an API
- charged for the text embedded
- often higher quality for trade vocabulary
- phrases leave your machine
An open model
- runs locally through Sentence Transformers
- costs nothing per call
- model card names clustering as a use
- nothing is sent to a third party
An open model such as all-MiniLM-L6-v2 runs locally through Sentence Transformers, costs nothing per call and sends nothing to a third party; its model card names clustering and semantic search as intended uses. A hosted model trades that for convenience and often quality. OpenAI's embeddings guide lists text-embedding-3-small at 1,536 numbers per vector and text-embedding-3-large at 3,072. Anthropic's own guide to embeddings names Voyage AI as one provider because Anthropic makes no embedding model of its own, which is why a project built in Claude Code still calls a separate service for this step.
No single model is best at everything. The authors of the MTEB paper, the Massive Text Embedding Benchmark, tested models across 8 kinds of task, 58 datasets and 112 languages and found that no particular text embedding method dominates across all of them. For a keyword list that means: pick a reasonable model, keep it fixed, and judge it on your own phrases. Three rules keep the step honest:
- Use one model for the whole list. Vectors from two models cannot be compared.
- Save the vectors with the model's name, so a new run of the algorithm never re-embeds.
- Embed new phrases only next quarter, and reuse the rest.
Measuring similarity between keywords with cosine similarity
Similarity between two keywords is measured by comparing their vectors, and the standard measure is cosine similarity: a score from the angle between two vectors, higher meaning closer in meaning. It ignores a vector's length and reads only its direction, which suits text, where what matters is what a phrase is about.
Where the spot check expects phrases to land
Far apart
Close in meaning
- patio heatera sign the cleaning or the model is wrong
- paving slab pricesclose by topic, a different intent
- a paved terracethe same question in other words
You do not write this calculation. Sentence Transformers uses cosine as its default, and OpenAI's guide recommends it too. Google's course page on measuring similarity from embeddings explains the detail that matters: the dot product grows with a vector's length while cosine does not, so on vectors normalised to length 1 they agree. The result is a table with every phrase scored against every other.
Before clustering anything, read that table for a dozen phrases you know well. If "paving slab prices" sits among the nearest neighbours of "patio paving ideas", the model groups by topic and you will need to watch for intent in the review. If "patio heater" sits there, the cleaning or the model is wrong for your vocabulary. Ten minutes here tells you more than any algorithm setting.
Clustering algorithms usually ask for a distance rather than a similarity. For cosine, distance is one minus similarity, so near-identical phrases sit close to zero; a threshold set the wrong way round gives one giant cluster or hundreds of single phrases.
Applying a keyword clustering algorithm
A keyword clustering algorithm takes the vectors and decides which form groups, and for keyword lists the practical choice is one that does not need the number of groups in advance. You rarely know how many questions a list hides; that is why you are clustering it.
What a keyword list asks of a clustering algorithm
- Agglomerative clustering a distance threshold, no number of groups needed
- HDBSCAN leaves outliers out, which is useful, but needs a minimum group size
- k-means the number of groups must be chosen before it starts
- Ward linkage with cosine it accepts only Euclidean distance
k-means needs the number of clusters before it starts; Google's page on the advantages and disadvantages of k-means says k must be chosen manually and that it struggles with clusters of varying sizes. Keyword lists are exactly that: one question may have forty phrasings and another two. Agglomerative clustering starts with every phrase alone and keeps merging the closest groups until the next merge would be too far apart. In scikit-learn's AgglomerativeClustering class you set a distance_threshold and leave n_clusters empty; cosine works with average or complete linkage, but not with the default ward linkage, which accepts only Euclidean distance.
HDBSCAN looks for dense regions and is happy to leave some phrases out. Google's overview of clustering algorithms describes density-based methods the same way: dense areas become clusters and outliers are not assigned to any. In scikit-learn's HDBSCAN class, groups smaller than min_cluster_size are left as noise and given the label -1. For keyword work that is a feature: a phrase that fits nowhere is a phrase a person should look at, not one to force into the nearest group.
Our default is agglomerative clustering with cosine distance and average linkage, because its one setting, the threshold, maps onto a question an editor understands: how close must two phrases be to share a page? Start cautious, read the groups, move it in small steps, and write every setting into a config file so the approved run can be repeated.
Building the system with Claude Code: a worked example
Building the system with Claude Code means describing each stage in plain language, letting Claude Code write the Python and its tests, and accepting each piece only once you have read it and seen the tests pass. The example is an illustration, not a client: a garden-design studio with two keyword exports and no cluster map.
The garden studio’s build, stage by stage
- >Read both CSV files and apply the five cleaning rules
- +clean.py and test_clean.py
- ·A test fails: the filler rule strips the word small
- >Keep small; embed every phrase and save the vectors
- ·Second run reuses the saved vectors and skips phrases already embedded
- >Group with agglomerative clustering, threshold from the config file
- +clusters.csv and the review sheet
- five short files and a config, every one readable
The first session sets the ground rules. A CLAUDE.md file for the project records what the system is for, the four roles, and one firm instruction: the model never decides groups, the script does. Anthropic's memory documentation says CLAUDE.md files are read at the start of every session, so next quarter's session starts from the same rules.
The project grows one stage at a time, in this order:
- Load and clean. "Read both CSV files, apply these five cleaning rules, and write a test for each rule from these examples." Claude Code writes
clean.pyandtest_clean.pyand shows the rows each rule removed. - Embed. "Embed every phrase with all-MiniLM-L6-v2, save the vectors with the model name, skip phrases already embedded."
- Inspect. "Print the ten nearest neighbours of these twelve phrases": the spot check, as a command.
- Cluster. "Group with agglomerative clustering, cosine distance, average linkage, threshold from the config file."
- Report. "List each group's phrases by impressions and flag any group mixing a price phrase with an ideas phrase." That is the review sheet.
Anthropic's guide to common Claude Code workflows lists writing tests as an everyday task, and it is the habit that matters most here. In the studio's first run, a test caught a cleaning rule that stripped "small" as filler, which merged "small garden design" into "garden design", two pages with different readers.
The result is five short files and a config, all readable, so someone else can run it next quarter. Our account of Claude Code for content automation describes the same file-by-file way of building for a whole publishing system, and our guide to a keyword clustering engine in Claude Code packages these steps as a skill with test cases. Inside a client's SEO content automation system, the cluster map feeds the briefs rather than sitting in a folder.
Reviewing and correcting inaccurate clusters
Reviewing clusters means a person reads every group, splits the ones that mix two search intents, merges the ones that are one question, and records each decision so the next run respects it. This step stays human: the algorithm measured closeness of meaning, and only someone who knows the business can say whether two close phrases want one page or two. Our guide to what to automate and what to keep draws the same line across a whole content process.
Two questions the reviewer asks of a cluster
Same object · same intent
Keep togetherone question, one page
Same object · different intent
Splitideas and planning permission want two pages
Different words · same intent
Mergelow maintenance and easy care are one question
Different object · different intent
Keep apartthe algorithm was right
Left column: the searcher wants the same thing
Right column: the searcher wants something different
In the garden studio's run, most groups were right on first reading. Three were not, and they are the three shapes of error you will meet on almost any list:
- Two intents in one group. "Garden room ideas" and "garden room planning permission" landed together: one reader wants pictures, the other a legal answer. Split.
- One question in two groups. "Low maintenance garden" and "easy care garden design" landed apart because the threshold was slightly tight. Merge.
- A phrase that belongs nowhere. "Garden centre near me" sat on the edge of the plants group, and the studio runs no garden centre. Remove it and add a drop rule.
Every correction goes into an overrides file in plain text, such as "always separate these two", and the script applies it after clustering, so a decision is made once and the threshold is never bent for one awkward pair. When the same override keeps recurring, change the rule in the code instead.
For the genuinely close calls, compare the search results: if two phrases bring up mostly the same pages, they want one page. It is slower, so save it for the groups the review flags.
How to export keyword clusters into an SEO structure
To export keyword clusters into an SEO structure, turn each approved group into one row that names the page, its primary phrase, its supporting phrases and the page you already own for it, then arrange those rows into hubs and the pages under them. A list of groups tells you what people ask; this table tells you what to build, what to improve and what to leave alone.
From approved clusters to a page plan
after review and overrides
from the Search Console export
current URLs and titles
one row per group, with its primary phrase
an existing page already answers it
a page under its hub
not worth a page yet
The export script writes one CSV: the group's label, its primary phrase (usually the one with the most impressions), the supporting phrases, total impressions, the existing URL if one of your pages already answers it, and an action: improve, write new, or leave. Matching against your current page titles is what stops a site writing the same article twice. An improve row is usually a new heading or a missing section on a page you already have, the outcome most buyer questions land on in our guide to answer pages versus existing content.
Groups then sit under a hub, a broad page the specific ones link up to and that links down to each of them; our explainer on content clusters, from knowledge to content covers how a pillar and its spokes are mapped and wired. That arrangement is the heart of SEO content clusters, and keeping the links as data lets them be checked rather than remembered.
- Each row becomes a brief. The group's primary phrase, its supporting questions and its impressions are what a writer needs; our guide to turning a Search Console query into a brief shows the same step for one platform, and the approved rows feed SEO content writing on your own site.
- The primary phrase belongs in the title once. Google's starter guide says that repeating the same words over and over is tiring for readers, and its spam policies define keyword stuffing as filling a page with keywords in an attempt to manipulate rankings. The supporting phrases are the questions the page answers, not words to repeat.
- One group, one page. If two rows point at the same new URL, the review missed a merge, and the export script should refuse to write the file until each URL appears once. That refusal is the same gate our guide to automating SEO content without spam puts before any new page is written.
Limitations of semantic keyword clustering, and what it costs to run
The main limitation of semantic keyword clustering is that it measures similarity of meaning, while what decides a page is the searcher's intent. Phrases about the same thing for different reasons, researching, comparing or buying, sit close together in embedding space, which is why the review step cannot be skipped however good the model is.
How much each limitation weighs
Relative, not measured
The other limits follow from how the parts work. The model knows language in general, not your field, so trade terms can land in odd places. The threshold is a judgement written as a number. And clustering sees neither demand nor ranking; whether a page ranks is a question for the measurement in our guide to measuring whether a content system works. Treat the output as an organised starting point, not a finished plan.
The running cost is mostly time: the first build, a few sessions with Claude Code, and an hour or two of review each quarter. An open model costs nothing per run, and a hosted one charges for text embedded, which for a keyword list is little. A workflow tool such as n8n can start the quarterly run and wait for the reviewer's approval while the clustering stays in Python, as our guide to content automation in n8n shows for a wider workflow. If you would rather have it built and handed over, our content automation services cover it.
Frequently asked questions
Can I do semantic keyword clustering without writing Python?
Yes, but you give up the ability to see and change the method. Paid tools group a list for you, yet the settings behind the groups are usually hidden, so a disputed group cannot be traced to a cause. With Claude Code helping, the Python version is five short files.
Which embedding model is best for clustering keywords?
There is no single best model for every list; the MTEB benchmark found that no embedding method dominates across all tasks. Start with an open model like all-MiniLM-L6-v2, judge it with a nearest-neighbour spot check on your own phrases, and test a hosted model only if your trade vocabulary lands in the wrong places.
How do I choose the distance threshold for agglomerative clustering?
Start cautious, read the groups and move the threshold in small steps until most groups read as one question: tighten it if groups mix two intents, loosen it if one question is scattered. Record the value in a config file and fix the few awkward pairs with overrides.
Does Claude Code send my keyword list to Anthropic?
Claude Code sends what it reads into its session, so opening the keyword file in it shares that content. The clustering run itself needs no Claude Code at all: the script runs on your machine, and with an open embedding model nothing leaves it. For a sensitive list, let Claude Code work on the code and a small sample.
Why do some keywords end up in no cluster?
Some keywords end up in no cluster because nothing sat close enough to group them with, which HDBSCAN reports as noise with the label -1. Review them as their own list: each is a one-off, a topic you have not covered, or a phrase the cleaning should have removed.
How often should I re-run the clustering?
Re-run it when the inputs have changed, which for most sites means once a quarter after a fresh Search Console export. Embed only the new phrases, re-cluster with the same settings, apply the saved overrides and review what changed; a full rebuild is needed only when you switch embedding model.
Where to start
Export the last three months of queries from Search Console, pick twelve phrases you know well, and write down which others you would expect on the same page as each. That is your test before any code exists. Then open a folder in Claude Code, write a short CLAUDE.md naming the four roles, and ask for one script that embeds those twelve phrases and prints each one's nearest neighbours. If the output matches your notes, build the rest; if not, you learned it cheaply.
Disclosure
This post was written by Shreyas Dave, founder of Paper Eagle AI. We sell content automation services, which is the category this article is about, so we have a commercial interest in you concluding that a system beats ad-hoc effort — read it knowing that. No tool vendor was involved in writing it, nobody paid for a mention, and there are no affiliate links anywhere on this site. Where a third-party figure appears, it’s attributed to the publisher it came from; anything we couldn’t source is written as a direction rather than a number.
Paper Eagle AI builds Content Operating Systems that turn a business’s knowledge and expertise into consistent, multi-platform content, and we deliver them as content automation services. Working as a content automation specialist, we capture what a business knows and how it sounds, set the strategy, and build the workflows that research, draft, repurpose and publish — with a named person approving every piece before it goes out. Every build runs through discovery, design, build and handoff. The system lives in the client’s own accounts, it is documented, the team is trained to run it, and the business owns it outright. We don’t write content on a retainer, and we don’t build lead generation, CRM or sales automation.
One source of thinking becomes native content for every platform a business publishes on: the founder’s LinkedIn and the company page, YouTube and Shorts, Instagram and Reels, TikTok, Reddit, Medium, newsletters, and the company’s own website, written to be found in Google and understood by AI search. Our multi-platform content automation page shows how they share one source, and our case studies document the systems behind our own publishing, file by file. You can follow the work on the company’s own channels: Paper Eagle AI on Instagram, Paper Eagle AI on YouTube, the Paper Eagle AI company page on LinkedIn, Paper Eagle AI on Substack, Paper Eagle AI on Reddit and Paper Eagle AI on Medium. Paper Eagle AI is also listed where clients can review its work: Paper Eagle AI on Clutch, Paper Eagle AI on GoodFirms and the Paper Eagle AI Google Business Profile.
Keep reading
- How to automate keyword clustering — the two grouping methods side by side, and when shared search results beat shared meaning.
- Build an SEO keyword clustering engine in Claude Code — the same job packaged as a Claude Code skill with test cases and a pages table.
- How to automate internal linking — what to do with the hub-and-page table once the clusters are approved.