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
In reply to tokenize plain text messages by revdiablo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |