http://www.perlmonks.org?node_id=433913

Before I start, please note this is not strictly a Perl question. It is more of a general algorithms questions, and that's why I posted to Meditations.

A friend of mine has come up with a neat algorithm for creating a hierarchy from a messy bag of keywords. I was wondering if this was something novel or not, so I thought I would ask the Monks if anyone recognizes it.

Another reason I'm posting is simply because I like this algorithm. Whether it's new or not, it's simple and intuitive. It creates hierarchies in a way that seems natural and "right." I would like to hear other people's thoughts about it. Maybe there are some things I am overlooking.

The idea is to start with a list of items that have keywords assigned to them. The keywords are not necessarily chosen with a hierarchy in mind, yet by grouping commonly used keywords, a hierarchy can be synthesized. It goes something like this:

for each item in items: for each keyword in item.keywords: frequency{keyword}++ for each item in items: sort keywords by frequency push hierarchy{sorted keywords}, item

Thus, given the following items:

item = 1, keywords = a b c item = 2, keywords = b c item = 3, keywords = d b

The frequencies would be:

a = 1, b = 3, c = 2, d = 1

And the hierarchy would end up looking like:

b/c/2 b/c/a/1 b/d/3

Here's my quick and dirty Perl implementation, so there's something to actually play with:

my @items; push @items, { name => 1, keywords => [ qw( b ) ] }, { name => 2, keywords => [ qw( b c ) ] }, { name => 3, keywords => [ qw( b c ) ] }, { name => 4, keywords => [ qw( b d ) ] }, { name => 5, keywords => [ qw( e ) ] }, { name => 6, keywords => [ qw( e f ) ] }; my %freq; for (@items) { for (@{ $_->{keywords} }) { $freq{$_}++; } } my @nodes; for (@items) { my @keywords = sort { $freq{$b} <=> $freq{$a} } @{ $_->{keywords} }; my $path = join "/", @keywords, $_->{name}; push @nodes, $path; } print "$_\n" for sort @nodes

Update: funny that The Mad Hatter should mention tags. This was originally made to parse the tags from a http://del.icio.us dump and create a hierarchy of links from it. I used "keywords" instead of "tags" because I thought it would be a more generic term for essentially the same thing. :-)