zeroclickinfo-goodies/lib/DDG/Goodie/Frequency.pm

56 lines
1.2 KiB
Perl
Raw Normal View History

2012-05-06 08:13:52 -07:00
package DDG::Goodie::Frequency;
2012-05-07 18:38:06 -07:00
# ABSTRACT: Displays frequency of alphabet character (a-z)
2012-05-06 08:13:52 -07:00
use DDG::Goodie;
2012-05-07 18:38:06 -07:00
triggers start => 'frequency', 'freq';
2012-05-06 08:13:52 -07:00
2012-11-06 14:35:36 -08:00
primary_example_queries 'frequency of all characters in testing';
secondary_example_queries 'frequency of B in battle', 'frequency of all in testing 1234 ABC!';
description 'calculate the frequency of characters in a string';
name 'Frequency';
code_url 'https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DDG/Goodie/Frequency.pm';
category 'calculations';
topics 'geek';
2012-11-06 14:48:08 -08:00
attribution github => [ 'http://github.com/unlisted', 'Morgan' ];
2012-11-06 14:35:36 -08:00
2012-05-06 08:13:52 -07:00
handle remainder => sub {
if ($_ =~ /^of ([a-z]|(?:all ?|)(?:letters|characters|chars|)) in (.+)/i)
2012-05-06 08:13:52 -07:00
{
2012-05-07 20:37:31 -07:00
my $collect = lc $1;
my $target_str = lc $2;
# warn qq($collect\t$target_str\n);
2012-05-07 10:56:19 -07:00
my $count = 0;
2012-05-07 20:37:31 -07:00
my %freq;
my @chars = split //, $target_str;
foreach (@chars)
2012-05-06 08:13:52 -07:00
{
2012-05-07 20:37:31 -07:00
if ($_ =~ /[a-z]/)
2012-05-07 10:56:19 -07:00
{
if ($collect =~ /all|letters|characters|chars/) { ++$freq{$_}; }
2012-05-07 20:37:31 -07:00
else { ++$freq{$_} if $_ eq $collect; }
2012-05-07 10:56:19 -07:00
++$count;
};
2012-05-06 08:13:52 -07:00
};
my @out;
foreach my $key (keys %freq)
{
2012-05-07 18:38:06 -07:00
push @out, join ":", $key, $freq{$key} . "/" . $count;
};
return "Frequency: " . join ' ',sort(@out) if @out;
2012-05-06 08:13:52 -07:00
};
return;
};
zci is_cached => 1;
1;