revdiablo has asked for the wisdom of the Perl Monks concerning the following question:
Hi there. I have a toy project I'm working on to do some basic stats on plain text. Obviously I need to tokenize this text so I can count words, and whatnot. I have come up with two approaches; one using s/// most of the time, the other using map, split, foreach, and friends. The version using s/// benchmarks about 78% faster, but that's not really my question. I just wonder if there are any ideas how to make either of these cleaner/simpler/more better.
Without further adieu, here are the subroutines in question:
First, the version that uses list ops:
sub tokenize_msg_w_lists { my ($msg) = @_; # define consitituent characters. my $con = 'A-Za-z0-9\'\$!,.-'; # first pass. split tokens on any non-consitituent characters. my @words = map {s/[,.]$//; $_} split /[^$con]+/, $msg; # second pass. split on , or . that aren't surrounded by digits. my %words; foreach (@words) { $words{$_}++ foreach split /(?<=\D)[,.](?=\D)/, + $_; } return keys %words; }
And here is the version that uses string ops:
sub tokenize_msg_w_strings { my ($msg) = @_; # define consitituent characters. my $con = 'A-Za-z0-9\'\$!,.-'; # separate tokens with % for later splittage $msg =~ s/[^$con]+/%/g; # replace any non-cons with % $msg =~ s/%[,.]/%/g; # delete [,.] in the front of a t +oken $msg =~ s/[,.]%/%/g; # delete [,.] in the back of a to +ken $msg =~ s/^[,.]//g; # delete [,.] at the start of a l +ine $msg =~ s/[,.]$//g; # delete [,.] at the end of a lin +e $msg =~ s/(?<=\D)[,.](?=\D)/%/g; # delete [,.] not surrounded by d +igits my %words = map {$_=>1} split /%/, $msg; return keys %words; }
In case you haven't gathered the requirements by looking at the code, I basically want to split on any characters other than alphanumeric and ['$!,.-]. And I only want to keep , and . if they're surrounded by digits. So if my text message is "This, is, an, example. Keep $2.50, 1,500, and 192.168.1.1." I want it to be tokenized as follows: This | is | an | example | Keep | $2.50 | 1,500 | and | 192.168.1.1
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: tokenize plain text messages
by BrowserUk (Patriarch) on May 10, 2003 at 00:15 UTC | |
by revdiablo (Prior) on May 10, 2003 at 01:55 UTC | |
by BrowserUk (Patriarch) on May 10, 2003 at 02:32 UTC | |
by revdiablo (Prior) on May 10, 2003 at 04:13 UTC | |
by BrowserUk (Patriarch) on May 10, 2003 at 06:03 UTC | |
| |
|
Re: tokenize plain text messages
by Enlil (Parson) on May 10, 2003 at 01:41 UTC | |
|
Re: tokenize plain text messages
by rinceWind (Monsignor) on May 10, 2003 at 12:07 UTC | |
by revdiablo (Prior) on May 10, 2003 at 18:00 UTC | |
by bart (Canon) on May 11, 2003 at 00:38 UTC | |
by revdiablo (Prior) on May 11, 2003 at 09:02 UTC | |
|
Re: tokenize plain text messages
by artist (Parson) on May 10, 2003 at 01:31 UTC |