rizzy has asked for the wisdom of the Perl Monks concerning the following question:
I need to search a very large number of html files for several keywords and save the paragraph containing the word(s) (the line before and after will do). I can do it with the following, but it takes a great deal of time. Given that I need to do hundreds of thousands of files, the minute or so that it takes for each one is unacceptable (will take months at this rate):
#!/usr/bin/perl -w use strict; use LWP::Simple; open ("output","> outputfile.txt") || die ("Could not open output file + $!"); my $html = get("http://www.htmladdress.com/file.html") or die "Couldn't fetch the site."; while($html=~ m{(.+\n.+(key\sword1|key\sword2|key\sword3).+\n.+)}gim){ + my $text =$1; $text =~ tr[\n][ ]; print output "$text\n"; } close ("output");
I've made it more simple than it is in practice. Basically, I get the html file and search for the following sequence: a line, a line break, a line with one of my keywords, a line break, and another line. I think it is taking a long time because I've included such a long sequence of characters to search for. If I don't tell it to look for the surrounding lines (i.e., .+\n.+), it is much quicker (seconds versus minutes).
Ideally, I'd like to identify only my keyword and then save the the previous line, the current line(s), and the subsequent line. Anybody know a way to do this that would speed things up? Also, I want to be able to match a phrase across line brakes, so this might complicate things.
Any help would be greatly appreciated!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: FAST way to pull multiple lines around a keyword
by moritz (Cardinal) on Oct 19, 2010 at 18:23 UTC | |
|
Re: FAST way to pull multiple lines around a keyword
by CountZero (Bishop) on Oct 19, 2010 at 18:22 UTC | |
by rizzy (Sexton) on Oct 19, 2010 at 19:10 UTC | |
|
Re: FAST way to pull multiple lines around a keyword
by ig (Vicar) on Oct 19, 2010 at 19:31 UTC | |
|
Re: FAST way to pull multiple lines around a keyword
by aquarium (Curate) on Oct 19, 2010 at 22:16 UTC |