文字列のリストがあり、そのリストからランダムに文字列を取得したい。誰か perl か awk で私を助けてくれませんか。
文字列リスト:
John
Peter
Adam
Mike
Charlie
Sanders
William
...
出力:
Peter
Mike
Sanders
...
ファイルにそれらの名前があると思います。
use File::Slurp qw(read_file);
use List::Util qw(shuffle);
print for (shuffle read_file 'the_input_file_name' )[0..499];
List::Util
モジュールは演算子を提供しますshuffle
。これはコアモジュールでもあるため、インストールする必要はありません
use strict;
use warnings;
use List::Util 'shuffle';
open my $fh, '<', 'string_list.txt' or die $!;
my @names = <$fh>;
print for (shuffle @names)[0..499];
あなたの言葉、各行に新しい言葉を含むファイルを作成します。次に、このスクリプトを実行して、リストから選択した数の単語(以下の例は5つを示しています)を選択します。
#!/usr/bin/perl -l
sub random_words {
$random_items = $_[0];
open(DB, 'random-words.db');
@words = <DB>;
close DB;
for ($i=0; $i < $random_items; $i++) {
$random_index = int(rand(@words));
$random_word = $words[$random_index];
$random_word =~ s/\R//g;
print $random_word;
}
}
random_words(5);
print splice(@a,rand(@a),1),"\n" while @a;
where @a our list ge my @a = qw/ John Peter Adam Mike Charlie Sanders William /;