我有一个字符串列表,我想从列表中随机选取字符串。你能帮我解决perl或awk问题吗?字符串列表中的随机字符串
字符串列表:
John
Peter
Adam
Mike
Charlie
Sanders
William
...
输出:
Peter
Mike
Sanders
...
我有一个字符串列表,我想从列表中随机选取字符串。你能帮我解决perl或awk问题吗?字符串列表中的随机字符串
字符串列表:
John
Peter
Adam
Mike
Charlie
Sanders
William
...
输出:
Peter
Mike
Sanders
...
创建你的话一个文件,每行一个新词。然后运行该脚本从列表中选择一个选定的数字(下面的示例显示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);
我假设你在文件中有这些名字。
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];
print splice(@a,rand(@a),1),"\n" while @a;
其中@a我们的名单G.E. 我@a = QW/ 约翰 彼得 亚当 迈克 查理 桑德斯 威廉 /;
你在Linux上吗?有'sort --random-sort ...' – mob 2012-08-16 18:15:00
也试试'shuf'。 – kev 2012-08-16 18:20:57
@mob认真吗?酷..不知道,存储以备将来使用。 – Levon 2012-08-16 18:27:28