How to build a keyword clustering tool with Python

Search Engine Land by 7 min read 669x views
How to build a keyword clustering tool with Python

Share Post

Keyword grouping is 1 of those SEO tasks that sounds elemental until you’re staring astatine a spreadsheet pinch 12,000 rows and a “group by intent” file you’re filling successful by hand.

Manual clustering doesn’t scale, and rule-based grouping misses the semantic overlap betwixt phrases that don’t stock a azygous connection but intelligibly beryllium together.

I’ve refactored a keyword clustering book that I developed a fewer years ago. The model uses TF-IDF vectorization to make characteristic vectors, which are past clustered utilizing HDBSCAN, a density-based clustering algorithm. You tin find the book here.

The problem pinch keyword clustering

Keyword clustering is the catalyst for taxable generation. Rather than briefing contented writers pinch hundreds of individual keywords, clustering allows you to group semantically related queries into coherent topics, making it overmuch easier to nutrient contented that satisfies a wider scope of hunt intent.

The consequence is simply a set of topics that tin fortify semantic relationships, topical authority, soul linking, and visibility crossed related queries.

There are 2 cardinal challenges here: preprocessing the information and clustering the topics.

Preprocessing the data

SEO keyword exports are often noisy, particularly if they travel from your ain databases. Removing stopwords and non-ASCII characters can’t beryllium done manually, hence the request to automate information cleaning astatine scale.

Python is simply a straightforward solution because it provides the elasticity to build a pipeline that tin clean, normalize, and toggle shape ample keyword datasets pinch minimal manual intervention.

Clustering the topics 

When analyzing keyword data, you seldom cognize really galore topical groups beryllium until you’ve explored the dataset. This makes algorithms specified arsenic k-means a mediocre fit, arsenic they require you to specify the number of clusters successful advance.

A operation of TF-IDF and HDBSCAN proves peculiarly effective. TF-IDF transforms each keyword into a numerical vector by assigning greater weight to position that are unique wrong the dataset while down-weighting those that look often crossed galore keywords.

These vectors are past fed into HDBSCAN, a density-based clustering algorithm that identifies earthy groupings without requiring the number of clusters to beryllium defined successful advance.

One of HDBSCAN’s cardinal advantages is its expertise to place noise. Rather than forcing each keyword into a cluster, it assigns outliers to a -1 label, which intends it excludes keywords that don’t beryllium to immoderate topic.

From keywords to clustersFrom keywords to clusters

This is particularly valuable for SEO datasets, wherever keyword exports often incorporate highly circumstantial long-tail queries that don’t people fresh into broader thematic groups. 

Instead of degrading cluster value by assigning these position arbitrarily, HDBSCAN isolates them, producing cleaner and much coherent topical clusters.

Be the marque customers find first.

Track, grow, and measurement your visibility crossed Google, AI search, social, local, and each transmission that influences buying decisions.

Start your free trial

Sourcing the keyword database from BigQuery 

Before immoderate clustering happens, you request a keyword database — and if your Search Console spot is already exporting to BigQuery, that’s a amended root than the UI export, since it isn’t capped astatine 1,000 rows and isn’t sampled.

A elemental propulsion against the modular GSC BigQuery export schema looks for illustration this:

Sourcing the keyword database from BigQuery Sourcing the keyword database from BigQuery 

Export the consequence arsenic a CSV, portion it down to a azygous query column, prevention it arsenic a .txt record pinch 1 keyword per line, and that’s your clustering input.

If you don’t person BigQuery export group up, you tin still activity pinch Search Console data, but you’ll person a much constricted dataset to activity with.

In immoderate case, you tin export queries from the Search Console interface, arsenic the notebook only cares that you provender it a database of keywords.

Prompting the AI

A fewer years ago, I would get on pinch a little polished type of this script.

AI made the pursuing things easier erstwhile rebooting and fine-tuning the book for enhanced output.

Asking for tunable parameters, not hardcoded ones

Cluster sensitivity and minimum cluster size behave very otherwise depending connected whether you’re clustering 50 keywords aliases 50,000. Requesting these arsenic adjustable variables up apical meant I could retune without rubbing the logic.

Specifying the environment

The first type was a plain Python book meant to tally from a terminal. Since the existent workflow is “pull keywords, tally notebook, manus a customer a file,” I asked for a Google Colab-specific version, which changes the style of the codification (try/except blocks astir Colab-only imports, nary argparse) much than a mini tweak would suggest. It besides enabled amended visualization by leveraging Plotly to the fullest.

Get the newsletter hunt marketers trust on.


Running the code

The gist of the book was and remains simple. It takes successful a level database of keywords and automatically groups them into taxable clusters.

All you person to do is upload a .txt record pinch 1 keyword per line, and it cleans the matter (stripping typical characters, stopwords, and non-English entries).

Using tunable parameters is the cardinal to the full framework. Play astir pinch the sensitivity and min_cluster_size parameters. Adjust them based connected the size of your keyword list.

Running the codification - parametersRunning the codification - parameters

Once you’re happy pinch the number of clusters, TF-IDF is utilized to people really important each connection is wrong the set. HDBSCAN past finishes the process.

Each cluster gets an auto-generated explanation based connected its astir unique terms, and the results are exported to an Excel record pinch some a grouped cluster position and a afloat keyword-by-keyword breakdown. 

Running the codification - parameters and cluster scoresRunning the codification - parameters and cluster scores

Where AI adds value 

The decisions that really matter, from choosing TF-IDF complete connection embeddings to selecting HDBSCAN because the number of topics is unknown, still require an knowing of really keyword clustering works.

What AI removed was the repetitive activity of rebuilding boilerplate code, wiring libraries together, and refining the notebook into thing reusable.

The last consequence is simply a lightweight clustering instrumentality that tin process thousands of keywords successful minutes, producing a sensible first draught of your topical taxonomy. It won’t switch editorial judgment, but it will destruct hours of manual grouping and springiness your contented squad a acold much system starting point.

If you already export Search Console information into BigQuery, this becomes a earthy measurement successful your workflow: extract your queries, tally the notebook, reappraisal the clusters, and commencement readying contented based connected topics alternatively than isolated keywords.


Contributing authors are invited to create contented for MCP and are chosen for their expertise and publication to the hunt community. Our contributors activity nether the oversight of the editorial staff and contributions are checked for value and relevance to our readers. MCP is owned by Semrush. Contributor was not asked to make immoderate nonstop aliases indirect mentions of Semrush. The opinions they definitive are their own.


About the Author

Simone De Palma
Simone De Palma is simply a Technical SEO Manager astatine TUI UK Limited and laminitis of SEO Depths. Simone is besides a speaker astatine BrightonSEO, UK SEO Summit and a contributor to the Majestic SEO podcast.

He graduated successful Marketing and Management from IULM University earlier completing a grade successful Digital Marketing and Data Science astatine Leeds Beckett University. Simone has worked arsenic an SEO Specialist successful integer agencies successful Italy and the United Kingdom.

Simone De Palma has method SEO and web analytics acquisition moving pinch high-fashion eCommerce and Travel sites.
Other Article Search Engine Land
↑
Close Right Ads
Close Left Ads