Runner in the High

技術のことをかくこころみ

CUIでWeblioを使う

LTN with VX Connect
 

LifetouchNOTE用の手頃な日英辞書がなくて困っていたので作った。
HTML::TreeBuilderでweblioの単語検索結果ページをスクレイピングしているだけ。
単語の大まかな意味だけでもわかれば充分なので、割りといいハックだと思う。


#!/usr/bin/perl

#
# Weblio on CUI
#

use strict;
use warnings;
use LWP::UserAgent;
use HTML::TreeBuilder;

my $TARGET = "http://ejje.weblio.jp/content/";

if (defined($ARGV[0])) {
&startSearch($ARGV[0]);
} else {
print " Usage: weblio [QUERY]";
}

sub startSearch {
my $query = $_[0];
my $url = $TARGET.$query;
my $ua = LWP::UserAgent->new('agent' => "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)");
my $res = $ua->get($url);
my $content = $res->content;
my $tree = HTML::TreeBuilder->new;
my @items;
my $c;

print "QUERY: $query\n";
print "FETCHED: $url\n";
$tree->parse($content);
if (defined($ARGV[1])) {
if ($ARGV[1] eq "-full") {
@items = $tree->look_down("class", "level0");
} else {
print "Invalid options\n";
}
} else {
@items = $tree->look_down("class", "lvlB");
}

if ($#items != -1) {
foreach (@items) {
$c = $_->as_text;
print $c."\n";
}
} else {
print "No matching word\n";
}

$tree = $tree->delete;
}