gpt4 book ai didi

perl - 文件中最常用的字符串

转载 作者:行者123 更新时间:2023-12-02 02:11:05 25 4
gpt4 key购买 nike

我在这里找到一篇帖子,有人设法从文件中读取信息并整理出最常用的单词并返回每个单词被使用的次数。输入来自命令行参数,但我想执行相同的脚本,然后将要通过脚本运行的文件名作为输入。我找不到我做错了什么。

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);

我现在的结果是:

15                       0
15 0
10 0
10 0
10 0
5 1
5 0
5 0
5 0
5 0

我想要的结果是:

<word>             <number of occurances>
<word> <number of occurances>
<word> <number of occurances>
<word> <number of occurances>
<word> <number of occurances>
<word> <number of occurances>

最佳答案

线

printf "%-20s %5d\n", $seen{$_}, $_;

与您的意图相反。 $_是一个字符串,$seen{$_}$_在文本中出现的次数(一个数字), 所以你想说要么

printf "%-20s %5d\n", $_, $seen{$_};

printf "%5d %-20s\n", $seen{$_}, $_;

关于perl - 文件中最常用的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12823971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com