Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: Longest String Matching

by AnomalousMonk (Bishop)
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' -> ''

Replies are listed 'Best First'.
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?

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2019-08-17 10:41 GMT
Find Nodes?
    Voting Booth?
    If you were the first to set foot on the Moon, what would be your epigram?

    Results (134 votes). Check out past polls.