Perl 文件中最常用的字符串
我在这里找到一篇帖子,有人设法从文件中读取信息,整理出最常用的单词,并返回每个单词的使用次数。输入来自命令行参数,但我希望得到要执行的相同脚本,然后将要在脚本中运行的文件名作为输入。我找不到我做错了什么Perl 文件中最常用的字符串,perl,file,sorting,Perl,File,Sorting,我在这里找到一篇帖子,有人设法从文件中读取信息,整理出最常用的单词,并返回每个单词的使用次数。输入来自命令行参数,但我希望得到要执行的相同脚本,然后将要在脚本中运行的文件名作为输入。我找不到我做错了什么 print "Type the name of the file: "; chomp(my $file = <>); open (FILE, "$file") or die; while (<FILE>){ $seen{$_}++ for split /\W+
print "Type the name of the file: ";
chomp(my $file = <>);
open (FILE, "$file") or die;
while (<FILE>){
$seen{$_}++ for split /\W+/;
}
my $count = 0;
for (sort {
$seen{$b} <=> $seen{$a}
||
lc($a) cmp lc($b)
||
$a cmp $b
} keys %seen)
{
next unless /\w/;
printf "%-20s %5d\n", $seen{$_}, $_;
last if ++$count > 100;
}
close (FILE);
我想要的结果是:
<word> <number of occurances>
<word> <number of occurances>
<word> <number of occurances>
<word> <number of occurances>
<word> <number of occurances>
<word> <number of occurances>
两件事:
$seen
中,而不是$file
my $file= <>;
chomp($file);
my$file=;
chomp($file);
或简称:
chomp(my $file = <>);
chomp(我的$file=);
在第二行中,您希望将要打开的文件名放入$file,而不是$seen。因此:
chomp(my $file = <>);
chomp(我的$file=);
chomp去掉了末尾的换行符(从按enter键开始)。行
printf "%-20s %5d\n", $seen{$_}, $_;
与你的意图相反$\u
是一个字符串,$seen{$\u}
是文本中出现$\u
的次数计数(一个数字),因此您可以说
printf "%-20s %5d\n", $_, $seen{$_};
或
如果您告诉我们这是如何工作的,那会很有帮助。此程序没有产生您显示的输出:查看的
%中的计数不可能为零。但是除了Perl的质量很差之外,你的程序运行得很好。用不同的输入文件试试看啊,谢谢,我更改了很多次脚本,我不知道还有什么。谢谢,添加了chomp,但它没有更改脚本output@John如果解决了你的问题,请考虑将答案标记为“接受”。
printf "%-20s %5d\n", $_, $seen{$_};
printf "%5d %-20s\n", $seen{$_}, $_;