如何使用perl正则表达式解析wordpress博客中的文章?

时间:2013-10-27 03:31:04

标签: regex wordpress perl parsing

我正在构建一个应用程序,根据Linux桌面环境中的关键词进行一些文本挖掘。我的目标是使用wget从Wordpress站点列表下载网页,将页面保存到磁盘,然后将每篇文章分开以进行进一步处理。我的想法是,我可以根据某些单词的频率对单篇文章进行排序。 Wordpress博客中的文章倾向于遵循惯例:

 <article></article> 

与之间的实际记录。到目前为止,我已经提出了类似这样的perl代码:

  $site = "somepage.somedomain"; #can be fed from a database later
  $outfile = "out1.txt"; #can be incremented as we go along
  $wgcommand = "wget --output-document $outfile $site";
  system($wgcommand);

  open SITEIN, '<', $outfile;
  @sitebodyarr = <SITEIN>;
  close SITEIN;

  $pagescaler = join('', @sitebodyarr); #let us parse the page.

  #this is where I have trouble. the though is to look for a mated pair of tags.
  #word press documents are stored between <article> and </article>

  $article =~ m/<article>*<\/article>/$pagescaler/g;

  #I put the /g flag there, but it doesn't seem to get me
  #what I want from the string - *ALL* of the articles one-by-one.

是否有任何想法使这个匹配从html文档返回的所有文章标记对?

如果无法使用正则表达式,我的下一个想法是按顺序处理整个数组,捕获模式

   $line =~m/<article>/

然后启动一个字符串变量来保存文章内容。继续查询此变量,直到我捕获模式

   $line =~m/<\/article>/

然后将字符串 - 现在包含文章存储到我的数据库或磁盘,然后重复直到@sitebodyarr结束。但是如果可能的话,我真的很喜欢单行正则表达式。如果是,有人可以告诉我它会是什么样子吗?

2 个答案:

答案 0 :(得分:2)

查看包含Mojo suite等华丽模块的Mojo::DOM - 网页抓取变得轻松有趣。

use strict; use warnings;
use feature 'say';
use Mojo;

my $ua = Mojo::UserAgent->new;
my $request = $ua->get('http://example.com/');
if (my $resp = $request->success) {
  my $dom = $resp->dom();
  for my $article ($dom->find('article')->each) {
    say "$article";
  }
}

# short version:

say for Mojo::UserAgent->new->get('http://example.com/')->res->dom('article')->each;

您可以使用CSS选择器来导航DOM。

答案 1 :(得分:1)

==&gt;对于匹配从html文档返回的所有文章标记对的任何想法?

下面的代码将为您提供任何文章在html页面中出现的次数。

   #!/usr/bin/perl
    open $html_file_handle, "< $html_file";
    while(my $line=<$html_file_handle>) {
        if($line =~ /<article>(.+?)<\/article>/) {
            $counter_hash{$1}++;
        }
    }   
    foreach $article (keys %counter_hash) {
        print "$article  ==> $counter_hash{$article}\n";
    }