编辑:
在您的帮助下,我的脚本运行良好,非常感谢。
我还试图弄清楚如何保留标准输入选择,但仍然能够使用命令行“启动”,
我希望两者都能以 for ex 开始。 “perl wfreq.pl”,然后它询问用户什么文件,但我也希望能够通过说“perl wfreq.pl example.txt”来启动它,然后它不应该要求用户输入。
这可能吗?
#! /usr/bin/perl
use utf8;
use warnings;
print "Please enter the name of the file: \n" ;
$file = <STDIN>;
chop $file;
open(my $DATA, "<:utf8", $file) or die "Oops!!: $!";
binmode STDOUT, ":utf8";
while(<$DATA>) {
tr/A-Za-z//cs;
s/[;:()".,!?]/ /gio;
foreach $word (split(' ', lc $_)) {
$freq{$word}++;
}
}
foreach $word (sort { $freq{$b} <=> $freq{$a} } keys %freq) {
@fr = (@fr, $freq{$word});
@ord = (@ord, $word);
}
for ($v =0; $v < 10; $v++){
print " $fr[$v] | $ord[$v]\n";
}
最佳答案
如MVS wrote ,你需要使用“宇宙飞船”<=>
运算符和排序不是键,而是值。
这是应该有效的示例:
改变
foreach $word (sort keys %freq) {
print "$word $freq{$word}\n";
}
至
foreach $word (sort { $freq{$a} <=> $freq{$b} } keys %freq) {
print "$word $freq{$word}\n";
}
perldoc -f sort代码片段第 23-27 行包含相同的示例。
谈论编码:utf8 pragma documentation说用它来
enable/disable UTF-8 (or UTF-EBCDIC) in source code
要在文件输入中启用 UTF-8,您需要以特定模式(使用特定层)打开文件并将“utf8”层应用于 STDOUT:
open(my $DATA, "<:utf8", $file) or die "Oops!!: $!";
binmode STDOUT, ":utf8";
有关:utf8
的更多信息以及您可以阅读的其他 IO 层
关于Perl 频率排序和其他东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7804486/