MOON PHASEさんのアニメ番組表を整形する

http://www.moonphase.cc/Html/anime.html
のデータを整形するスクリプトを書いてみた。毎回番組改変期に参考にさせていただいているのだけど、コピペして日記に貼るのがもう少し楽になるといいかなーとおもって。

use strict;
use warnings;
use HTML::TableExtract;
use HTML::LinkExtor;
use HTML::TokeParser::Simple;

my $file   = shift;
my $parser = HTML::TableExtract->new(keep_html => 1);
my $table  = $parser->parse_file($file)->table(1,0);

foreach($table->rows){
  my $url  = get_link($$_[1]);
  my $data = strip_tag($$_[4]);
  my @row  = map { get_text($_) } @$_;
  my $time = ($row[3] =~ m|(\d{2}:\d{2})|) ? $1 : '-';
  next unless $row[0] =~ m|^\d{2}/\d{2}|;

  print "$row[0]\t$row[2]\t$time\t$row[1]\t$url\n";
  print foreach map {
    m| +(.+?) : (\d{2}/\d{2}) (\d{2}:\d{2})| ? "$2\t$1\t$3\t$row[1]\t$url\n" : ();
  } split(/\n/, $data);
}

sub get_link{
  my $content = shift;
  my $parser  = HTML::LinkExtor->new;
  $parser->parse($content);
  for ($parser->links){
    my($tag, %attr) = @$_;
    return (values %attr)[0] if $tag eq "a";
  }
}

sub get_text{
  my $text = strip_tag(shift);
  $text =~ tr/\x0A\x0D//d;
  $text =~ s/^\s+//;
  $text =~ s/\s+/ /g;
  return $text;
}

sub strip_tag{
  my $content = shift;
  my $parser  = HTML::TokeParser::Simple->new(string => $content);
  my $text    = '';
  while(my $token = $parser->get_token){
    next unless $token->is_text;
    $text .= $token->as_is;
  }
  return $text;
}

元データはwgetか何かでダウンロードしてることを想定してます。

$ perl te.pl anime.html
06/05   TBS     25:25   ヴァイス・サヴァイヴ    http://ws-tcg.com/anime/
06/24   CBC     25:29   うみものがたり〜あなたがいてくれたコト〜        http://www.sea-story.tv/
06/26   TBS     26:25   うみものがたり〜あなたがいてくれたコト〜        http://www.sea-story.tv/
06/27   HBC     26:13   うみものがたり〜あなたがいてくれたコト〜        http://www.sea-story.tv/
07/01   RKB     27:00   うみものがたり〜あなたがいてくれたコト〜        http://www.sea-story.tv/
07/02   TBC     25:34   うみものがたり〜あなたがいてくれたコト〜        http://www.sea-story.tv/
07/03   SBS     26:10   うみものがたり〜あなたがいてくれたコト〜        http://www.sea-story.tv/
07/03   RCC     26:40   うみものがたり〜あなたがいてくれたコト〜        http://www.sea-story.tv/
07/06   MBS     26:35   うみものがたり〜あなたがいてくれたコト〜        http://www.sea-story.tv/
07/20   AT-X    09:00   うみものがたり〜あなたがいてくれたコト〜        http://www.sea-story.tv/
06/25   AT-X    08:00   ファイト一発!充電ちゃん!!       http://juden-chan.jp/
06/29   NHK教育 07:40   うっかりペネロペ 第2シリーズ    http://www.penelope.tv/
..

あとは自分が見れる放映局でgrepすればOK。
それにしても、既存のモジュールがあるものはできるだけ使おうとしたのでHTMLタグの処理は全くしなくてよくなったんだけど、なんかこれだけのためにモジュール使いまくるのもオーバースペックという気はするなあ・・・。