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' -> ''
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|