Comments are inline.

use strict; use warnings; use Storable; use vars qw($CONTEXT_LINES $TEXTS %STOPWORDS $INDEX); $CONTEXT_LINES = 3; @STOPWORDS{ # Prefer reading these from a file. qw( the a an of and on in by with at he after into their is that they for to it them which) } = (); # prefer texts/*.txt over "chdir 'text'; glob '*.txt'" my @files = glob "texts/*.txt"; my %file_idx = map {; $_ => index_file( $_, $CONTEXT_LINES ) } @files; store \%file_idx, "../index/text.idx"; =pod { 'text.idx' => { word => [ 1, 3, 5, 6 ], another => [ 5, 7, 2, ] }, 'barfoo.txt' => { ....... } =cut sub index_file { my $filename = shift; my $lines_of_context = $_[0] > 0 ? shift() : 1; open my $fh, "<", $filename or die "Couldn't open $filename: $!"; my @offsets; my %index; while ( my $line = <$fh> ) { push @offsets, tell $fh; my $offset = scalar( @offsets ) < $lines_of_context ? $offsets[0] : shift @offsets; # Prefer ' ' over /\s+/ here. See perlfunc about this. for my $word ( split ' ', $line ) { $word = lc $word; # Prefer character classes to alternation when possible $word =~ s/[,.]$|[\][();:!]//g; next if exists $STOPWORDS{$word} # Prefer (\d+) to (\d)+ (unless that is *really* what + you mean) or $word =~ /p\.(\d+)/ # Remove the '?' as that makes the operation always s +ucceed. or $word =~ /-{5,}/; push @{ $index{$word} }, $offset; } } close $fh or warn "Couldn't close $filename: $!"; return \ %index; }

In reply to Re: Re: Re: Re: Re: Simple Text Indexing by diotalevi
in thread Simple Text Indexing by cyocum

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.