Python NLTK – Generate basic Anagrams

In this post we will be creating a Python script that will generate anagrams, to do this we will be using NLTK short for the natural language toolkit. This consists of a suite of libraries dedicated to natural language processing also known as NLP.

Anagrams are words or phrases that are formed using the letters within another word or phrase, typically each letter can only be used once and all letters are used. See a few anagram examples below.

  1. inch = chin
  2. elbow = below
  3. state = taste
  4. schoolmaster = the classroom

In this example we will be creating a basic anagram generator that will generate a single word from the letters within a given single word.

See the sample of Python code below where we generate anagrams based on input from user, the script then retrieves all permutations of the word. Any permutations that are none words or the word itself are dropped. Results are then returned to output.

import nltk
import itertools

def generate_anagrams(word):
    permutations = [''.join(p) for p in itertools.permutations(word)]
    anagrams = list(set(permutations) - set([word]))
    words = set(nltk.corpus.words.words())
    anagrams = [a for a in anagrams if a in words]
    return anagrams

while True:
    word=input("Enter Word: ")

An example of the above’s running can be seen below. The time taken to run will vary depending on the length of your word.

Please Enter your Word: listen
['enlist', 'tinsel', 'silent']

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply