2013-10-27 27 views
-1

我正在構建一個應用程序,根據Linux桌面環境中的關鍵詞進行一些文本挖掘。我的目標是使用wget從Wordpress網站列表中下載網頁,將頁面保存到磁盤,然後將每篇文章分開以供進一步處理。我的想法是,我可以根據某些單詞的頻率對單行文章進行排名。 Wordpress博客中的文章傾向於遵循約定:如何使用perl正則表達式分析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>/ 

,然後開始一個字符串變量來保存文章的內容。繼續concating這個變量,直到我趕上模式

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

然後存儲字符串 - 將現包含文章到我的數據庫或磁盤,然後重複,直到@sitebodyarr結束。但如果可能的話,我真的很喜歡單線程正則表達式。如果是,有人可以告訴我它會是什麼樣子?

+0

您應該使用XML解析器。 'XML :: Simple'可能足以做你想做的事。 http://stackoverflow.com/questions/6751105/why-its-not-possible-to-use-regex-to-parse-html-xml-a-formal-explanation-in-la – Cfreak

+2

你確定你想要[用RegEx解析HTML](http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html)? – brasofilo

+0

你知道在我腦海的某個地方,編碼恐怖文章確實泡了。但我不理會Atwood先生的警告,因爲,當它全部採用相同的格式時,它只是一個將段落從wordpress中拉出來的有限領域 - 與在有限情景中尋找一對標籤相比,並不是那麼充分的解析。雖然鏈接爲+1! – Micah

回答

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。

+0

可能是一個比試圖用RegEx來解決這個問題更好的選擇。而且它可以完成我所需要的工作,而無需編寫類似於堆棧的東西,以便在字符串中保存標籤以便開始和結束文章標籤。謝謝你。 – Micah

1

==>使這個匹配從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"; 
    }