Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Longest String Matching

by AnomalousMonk (Monsignor)
on Apr 09, 2013 at 01:40 UTC ( #1027617=note: print w/ replies, xml ) Need Help??


in reply to Longest String Matching

I don't know if this will be as fast as pemungkah's approach, but the Perl regex engine builds a trie for alternations, so even quite large alternations (354K words in Moby file) are very fast. The big time sink is reading all the words and building the alternation string in the first place, but of course this could be done in a separate step and the resulting joined string saved to a file for later quick access. (Also note that the dictionary file I'm using has oddities such as 'words' like "d's" and "e's", and apparently every letter of the alphabet appears as a word.)

>perl -wMstrict -le "my $wordlist = shift // die 'no wordlist filename given'; open my $fh_wordlist, '<', $wordlist or die qq{opening '$wordlist': $!}; my $words = join '|', sort { length($b) <=> length($a) } map { chomp; $_; } <$fh_wordlist> ; close $fh_wordlist or die qq{closing '$wordlist': $!}; ;; my @lexicon = qw( no now know known unknown antidisestablishment husband wife husband's wife's xyzzy a ); for my $word (@lexicon) { my ($longest_at_end) = $word =~ m{ \B ($words) \z }xms; print qq{'$word' -> '$longest_at_end'}; } " ..\..\moby\mwords\354984si.ngl 'no' -> 'o' 'now' -> 'ow' 'know' -> 'now' 'known' -> 'own' 'unknown' -> 'known' 'antidisestablishment' -> 'disestablishment' 'husband' -> 'band' 'wife' -> 'ife' 'husband's' -> 'd's' 'wife's' -> 'e's' 'xyzzy' -> 'y' Use of uninitialized value $longest_at_end in concatenation (.) or str +ing at -e line 1. 'a' -> ''


Comment on Re: Longest String Matching
Download Code
Re^2: Longest String Matching
by space_monk (Chaplain) on Apr 09, 2013 at 14:27 UTC
    Someone ought to run Benchmark over the various proposals above and see which work out quickest (and under what circumstances)
    A Monk aims to give answers to those who have none, and to learn from those who know more.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1027617]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (11)
As of 2014-08-01 09:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (257 votes), past polls