[PHP] たくさんのキーワードからn個(n行)をランダムに選択する(抽出する)
いくつかのアイテムから n個をランダムに選択したいときがある。たとえば、人気のキーワードは日に数千あるけれど、上位10個を表示するだけだとランキング上位のキーワードが確固たる地位を築いてしまうだけで、おもしろくなかったりするので、そんなときは上位1000個から10個のキーワードをランダムに選択して表示するようにするといいじゃないかな。
たとえば、キーワードとその検索頻度を1行に並べた tsv形式のファイルが入力があるとする。例えば、
ほげほげ,123 ふがふが,110 .... かんぱり,32 なんとか,24
PHPで作るなら
<?
// number of output lines
$max=intval($argv[1]);
// open standard input
$h=fopen('php://stdin','r');
if (!$h) { die('stdin open error'); }
// put all lines into an array
$items=array();
while(!feof($h)) {
$line=trim(fgets($h));
if (!$line) { continue; }
$items[]=explode(',',$line);
}
fclose($h);
// shuffle the array of lines
shuffle($items);
// output selected lines
for($i=0;$i<$max;$i++) {
echo $items[$i][0]."\n";
}
?>
のようなコードで、標準入力から読み込んだキーワードから、指定した n個をランダムに選択(抽出)できる。たとえば、これを extract_n_randomly.php として保存し、
% php extract_n_randomly.php 10 < keywords.tsv
とすれば、実行するたびに異なる 10個 のキーワードを得る。
ポイントは shuffle() ( cf. PHP: shuffle – Manual ) で、配列をランダムに並べ替えてくれる。
Top page