Born Neet

- The Emotional Programmer -

Shortcut Key
Next Page … J(Shift + j)Prev Page … K(Shift + k)
Scroll Down … Space / Page Down
Scroll Up … Shift + Space / Page Up
2009.03.07(Sat.) 22:33
 

(ようやく)Perl始めました。

ちょっと前から入門書とかは読んだりしてたんだけど、
発売前から楽しみにしてた、

photo
モダンPerl入門 (CodeZine BOOKS)
牧 大輔
翔泳社 2009-02-10

by G-Tools , 2009/03/07

が、あまりにもわからなくて凹んだので。
やっぱプログラミングはコーディングして覚えないとね。

ちょうど記事タイトルのようなことがやりたかったこともあり、Perlで頑張ってみました。

というわけで、以下がPerl入門~サンプルコードによるPerl入門~(便利すぎ!!)を参考に作ったソースです。

ディレクトリ内htmlの英単語をカウント

ちなみに環境は、VMWare Playerでお手軽にVista上でLinux(Ubuntu) - Born Neetで入れたUbuntu。
perlやるならやっぱUnix系かな、と。(perlもcpanも元から入ってて楽だったし)

#!/usr/bin/perl

use strict;
use warnings;

my @files = glob '*.html';
my %count;

foreach my $file ( @files ) {
	open( my $fh, '<', $file ) or die "Can't open $file: $!";

	my $content;
	{
		local $/ = undef;
		$content = readline $fh;
	}

	$content =~ s/<head>.*<\/head>|<[^>]+?>//gs;

	my @words = split( /\W+/, $content );
	foreach my $word ( @words ) {
		if( $word ) {
			$count{ lc $word }++;
		}
	}
}

my @sorted = sort { $count{ $b } <=> $count { $a } } keys %count;

foreach my $key ( @sorted ) {
	print $key ."\t" . $count{ $key }, "\n";
}

Google Language APIで翻訳

CPAN・モジュールのお勉強を兼ねて、Google AJAX Language APIで翻訳してみる。
参考→Google AJAX Language API で翻訳する/楽

#!/usr/bin/perl

use strict;
use warnings;

use WebService::Simple;

my $api = WebService::Simple->new(
	base_url => "http://ajax.googleapis.com/ajax/services/language/translate",
    	response_parser => "JSON",
    	params => { 
		v => '1.0',
		langpair => 'en|ja',
	},
);

sub translate {
	my $response = $api->get({
		q => shift,
	});
	return $response->parse_response->{ responseData }->{ translatedText };
}

print translate('test'); # 試験

これを1つ目のコードとマージして、

foreach my $key ( @sorted ) {
	print $key ."\t" . translate($key) . "\t" . $count{ $key }, "\n";
	sleep 1; 
}

みたいにすれば英単語を数えつつ、翻訳も出来る。
(googleに怒られないように一応1秒待つようにした)

結果と微調整

結果がこちら↓

$ head -20 analyze.txt
the	その	7280
quot	quot	4476
a	1つの	4280
to	?へ	4120
is	なる	3192
of	の	3088
and	および	2367
it	それ	2073
that	あの	1902
this	この	1804
in	インディアナ	1627
function	関数	1604
be	存在する	1322
can	?できる	1165
are	なる	1158
for	?のために	1093
you	あなた	1044
not	?でない	901
The	その	897

…とここで、大文字/小文字を区別しちゃってることに気づく。
(例:theとThe)

そう何度もgoogleにリクエストを送りたくないということで、
以下のような急造スクリプトで対応。
(全部小文字にして単語数を合計)

#!/usr/bin/perl

use strict;
use warnings;

open( my $fn, '<', 'analyze.txt' ) or die '$!';

my %lower;
my %ja;

while ( my $line = readline $fn ) {
        my ( $en, $ja, $c ) = split( "\t", $line );
        $lower{ lc $en } += $c;
        $ja{ lc $en } = $ja; 
}

foreach my $word ( sort { $lower{ $b } <=> $lower{$a} } keys %lower ) {
        print $word . "\t" . $ja{$word} . "\t" . $lower{$word} . "\n";
}

微調整した結果がこちら↓
ちゃんとtheとTheが合計されてる。

スクリプトには無駄が多そうだけど、初めだし、期待通り動いてるのでまぁよしとする。

$ head analyze2.txt
the	その	8177
a	1つの	4499
quot	quot	4476
to	?へ	4240
is	なる	3198
of	の	3106
and	および	2439
it	それ	2403
this	この	2249
that	あの	1944

つまづいたとこ

perlcodesampleがかなり充実してたので、コーディング自体は特に困らなかった。

一番時間かかったのはCPANのモジュールを使うところ。
以下その時のメモ。

まずは、

$ cpan

で設定。
全部Enter連打で。
Enterで駄目なところは地域・国・サーバの指定ぐらいなので、そこは適当に番号で選ぶ。

設定が終わると、プロンプトが

cpan>

になるので

cpan> install WebService::Simple

等、インストールしたいモジュール名を入れる。
あとは依存してるモジュールとかも勝手に入れてくれるので、(またもや)Enter連打で答えていく。

インストールが終了したら、

cpan> q

で終了。
とここまでは特に問題はなかった。

が、モジュールを使用したファイルを実行すると、

Can't locate WebService/Simple.pm in @INC

と怒られた。

(いろいろ苦労しつつ)結局、

$ perl -I/home/ユーザ名/.cpan/build/WebService-Simple-0.15/lib ファイル名.pl

でいけたけど…
なんか面倒くさい、本当にあってるのか?

2009/03/08 15:40 追記

やっぱ間違ってました。

perlcodesampleさんからコメントもらった(ありがとうございます!)ので改めてやり直してみると、
テストで、

#   Failed test 'param is uri escaped'
#   at t/01_escape.t line 16.
#          got: '?param=%E7%8C%AB'
#     expected: '?param='
# Looks like you failed 1 test of 2.

なんてエラーが出てた。

ダメもとで、'param is uri escaped'で検索したら、
URI::Escapeってモジュールがあったので、これだ!と思ってinstall。

sudo cpan
cpan> install URI::Escape
cpan> install WebService::Simple

無事、

perl ファイル名.pl

だけでいけるようになりました。

モジュール自体に必要なものは自動でインストールされるけど、
テストで使ってるやつはそうじゃないってことなのかな?

やっぱわからないことだらけだなー。
頑張ろーっと。

2009/03/08 16:00 追記2

インストールされた場所を確認しようとしたら、

perldoc -l WebService::Simple
You need to install the perl-doc package to use this program.

なんてエラーが出るので、

sudo aptitude install perl-doc

とかやる必要有り。

perldoc -l WebService::Simple
/usr/local/share/perl/5.8.8/WebService/Simple.pm

Ubuntu(debian)特有っぽい。よくわかんないけど。

拍手[0回]

Post your Comment
Name (任意) :
Title (任意) :
URL (任意) :
Comment (日本語必須) :
無題
 cpanでインストールすると、-I オプションで指定しなくても、普通に使えるはずですけどね。
 make install のところで失敗してるのかも知れませんね。権限とか大丈夫でしょうか?

 もしインストールされてたら
perldoc -l WebService::Simple
でインストールされた場所が見れます。

 あと@INCはライブラリの検索パスですので、プログラムから出力してみると何かがわかるかもしれません。


 
perlcodesample: 2009.03/07(Sat) 22:57
Re:無題
perlcodesampleさん

コメントありがとうございます。
記事にも追記しましたが、テストで失敗しててインストールできてませんでした、
すいません。。。

これからも「Perl入門~サンプルコードによるPerl入門~」で、
いろいろと勉強させてもらいたいと思います。
2009/03/08(Sun)
Trackback

※ 日本語必須


この記事のトラックバックURL:
  BackHOME : Next 
自作スクリプト実験
ブログ内検索
カレンダー
01 2010/02 03
S M T W T F S
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28
最近のコメント
[12/29 佐藤]
[11/12 nontan]
[10/27 htakumu]
[10/22 JUN]
[10/17 枚方市民]
最近のトラックバック
RSS
RSS 0.91
RSS 1.0
RSS 2.0
プロフィール
HN:
t*
運営日数:
?日
記事数:
?件

ブログパーツ
あわせて読みたい
スポンサード リンク

Born Neet wrote all articles. 
Powered by Ninja.blog / TemplateDesign by TMP, modified by t*  

SEO忍者ブログ