Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use Data::Dumper;
- use List::Util qw/sum/;
- use strict;
- my $db={};
- my $texts={};
- sub words($){
- my($text)=@_;
- my(@lcwords,@whitespace,@words);
- while($text=~/(\w+)(\W*)/g){
- push @lcwords,lc $1;
- push @whitespace,$2;
- push @words,$1;
- }
- \@lcwords,\@whitespace,\@words
- }
- sub process($$){
- my($title,$text)=@_;
- return if $texts->{$title};
- $texts->{$title}=$text;
- my $position=0;
- my($words,$whitespace)=words $text;
- for(@$words){
- $db->{$_}->{$title}||=[];
- push @{ $db->{$_}->{$title} },$position++;
- }
- }
- sub find0($$$$){
- my($index,$words,$title,$startPosition)=@_;
- return if $index>=@$words;
- my $word=$words->[$index];
- my $best=-1;
- my @bestRes=(-1);
- for my $position(@{$db->{$word}->{$title}}){
- $startPosition=$position if $index==0;
- next if $position<$startPosition;
- my(@res)=find0($index+1,$words,$title,$position);
- my $endPosition=$res[-1];
- next if $endPosition==-1;
- if($best==-1 || $endPosition-$startPosition<$best){
- $best=$endPosition-$startPosition;
- @bestRes=($position,@res);
- }
- }
- @bestRes
- }
- sub find($){
- my($line)=@_;
- my($words)=words $line;
- my(@titles)=grep{ my $name=$_; @$words==sum map{ defined $db->{$_}->{$name}?1:0 } @$words } keys %$texts;
- my @res;
- for(@titles){
- my @data=find0 0,\@$words,$_,-1;
- my %map=map{$_=>1}@data;
- my $match;
- my $length;
- my(undef,$whitespace,$words)=words $texts->{$_};
- for($data[0]..$data[-1]){
- $match.="<b>" if $map{$_};
- $match.=$words->[$_],$length+=length $words->[$_];
- $match.="</b>" if $map{$_};
- $match.=$whitespace->[$_],$length+=length $whitespace->[$_] if $_!=$data[-1];
- }
- $match=~s/\n/ [newline] /gs;
- push @res,{title=>$_,text=>$match,score=>$length};
- }
- [sort{$a->{score} <=> $b->{score}}@res]
- }
- process "Elvis Presley - What's She Really Like",<<HERE;
- You're asking if she loves me
- Well, you don't know the half
- You're wondering if she'll leave me
- Ha, ha, ha, don't make me laugh
- HERE
- process "Bonnie Raitt - Any Day Woman Lyrics",<<HERE;
- If she's a woman, she'll try to make it last
- If you're a man now you'd better end it fast
- There's no reason here, no treason here
- Just the way a woman's mind, well she has no name
- She has no shame, she just loves you
- HERE
- process "Beatles - She Loves You",<<HERE;
- She loves you, yeah, yeah, yeah
- She loves you, yeah, yeah, yeah
- She loves you, yeah, yeah, yeah, yeah
- You think you lost your love
- When I saw her yesterday
- It's you she's thinking of
- And she told me what to say
- She says she loves you
- And you know that can't be bad
- Yes, she loves you
- And you know you should be glad
- HERE
- print Dumper find "she loves you";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement