On taking a closer look at your question, I realized that in my initial reply, I had missed something in your description, and the suggested script will produce more output than you wanted.

For the words in wordlist.txt that contain one or more of the words in master.txt as a substring -- e.g. "accumbering", which contains both "accumb" and "accumber" -- you want to associate the wordlist word with the master word that constitutes the longest match -- i.e. "accumbering" should be listed with "accumber", not with "accumb". Have I got that right?

To do that, the approach is a little more detailed:

use strict; # mustn't forget that open(LIST, "wordlist.txt"); open(MSTR, "master.txt"); # get the wordlist my @wordlist = map { chomp; $_ } <LIST>; # get the master list, sorted by word length, longest words first my @master = sort { length($b) <=> length($a) } map { chomp; $_ } <MST +R>; # declare a hash to hold the findings: my %report; foreach my $lookfor ( @master ) { foreach my $lookat ( @wordlist ) { if ( $lookat =~ /$lookfor/ ) { $report{$lookfor} .= ",$lookat"; $lookat = ""; # erases this word from @wordlist } } } foreach my $word ( sort keys %report ) { $report{$word} =~ s/,/ /; # change initial comma to space print "$word:$report{$word}$/"; }

By seeking out the longest master words first, and "erasing" the hits from the wordlist array as you find them, each wordlist element will only be listed once, with the longest matching master word.

update:Chmrr's correction to my initial response came in while I was working on this one. He's right: his version will be more efficient (and he helped me fix a typo).


In reply to Re: word association problem by graff
in thread word association problem by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.