Lesson
7
練習問題A
1. sort1.pl を参考にして,英文テキストに現れる単語を次の順番で並べ替えるスクリプトを書きなさい。
元のsort1.pl
----- -----
while
(<>) {
push (@words, split);
}
foreach $i (sort {$a cmp $b} @words) {
print $i . "\n";
}
exit;
----- -----
a. 大文字小文字を区別せずにアルファベット順でソート
while (<>) {
push (@wds, split);
}
foreach
$i (sort {lc $a cmp lc $b} @wds) {
print $i . "\n";
}
exit;
b. a.の逆順 (Z/z → A/a) でソート
while (<>) {
push (@wds, split);
}
foreach
$i (sort {lc $b cmp lc $a} @wds) {
print $i . "\n";
}
exit;
c. 単語を語尾から比較し,アルファベット順でソート (-a で終わる単語が -b で終わる単語よりも先に来る。)
while (<>) {
push (@wds, split);
}
foreach
$i (sort {lc (reverse $a) cmp lc (reverse $b)} @wds) {
print $i . "\n";
}
exit;
d. 各単語の文字数でソート
while (<>) {
push (@wds, split);
}
foreach
$i (sort {length $a
<=> length $b} @wds) {
print $i . "\n";
}
exit;
2. longleg.txt に含まれる文を,文字数の大きいものから小さいものへと並べ替えなさい。以前作成した1行1文に整形したテキストを利用すること。
while (<>) {
next if (/^\s*$/);
s/^\s+//;
s/\s+$//;
push (@sentences,
split (/\n+/, $_));
}
foreach
$i (sort {length
$b <=> length $a} @sentences) {
print $i . "\n";
}
exit;
> perl script/sort1-5.pl
sentenceslongleg.txt
3. 適当なファイルを対象に
sort2.pl と wordfreq1.pl を実行しなさい。出力結果を確認し,なぜそうなるのか,スクリプトの内容を確認しなさい。
#何回も出てくる単語は1回のみ表示
while (<>) {
push (@words, split);
}
foreach $i (sort {$a cmp $b} @words) {
if ($prev ne $i) {
print $i . "\n";
}
}
exit;
wordfreq1.pl
#出現回数も数えて表示
while (<>) {
push (@words, split);
}
foreach $i (sort {$a cmp $b} @words) {
if ($i eq $prev) {
$count++;
}
else {
print "$count\t$prev\n";
$prev = $i;
$count = 1;
}
}
print "$count\t$prev\n";
exit;
----- -----