我正在编写一个 perl 脚本,其中应处理文本,然后为字典提供单词频率,然后对字典进行排序。这段文字摘自埃德加·坡的《金甲虫》,目的是计算所有单词的出现频率。但是我做错了,因为我没有输出。我什么时候做错了?谢谢。
open(TEXT, "goldenbug.txt") or die("File not found");
while(<TEXT>)
{
chomp;
$_=lc;
s/--/ /g;
s/ +/ /g;
s/[.,:;?"()]//g;
@word=split(/ /);
foreach $word (@words)
{
if( /(\w+)'\W/ )
{
if($1 eq 'bug')
{
$word=~s/'//g;
}
}
if( /\W'(\w+)/)
{
if(($1 ne 'change') and ($1 ne 'em') and ($1 ne 'prentices'))
{
$word=~s/'//g;
}
}
$dictionary{$word}+=1;
}
}
foreach $word(sort byDescendingValues keys %dictionary)
{
print "$word, $dictionary{$word}\n";
}
sub byDescendingValues
{
$value=$dictionaty{$b} <=> $dictionary{$a};
if ($value==0)
{
return $a cmp $b
}
else
{
return $value;
}
}
最佳答案
你的代码中有:
@word=split(/ /);
foreach $word (@words)
{
您在拆分期间将数组命名为 @word
,但您在 for 循环中使用数组 @words
。
@word=split(/ /);
应该是
@words=split(/ /);
byDescendingValues
例程中的另一个拼写错误:
$value=$dictionaty{$b} <=> $dictionary{$a};
^^
正如其他答案中所建议的,你真的应该添加
use strict;
use warnings;
使用这些你可以很容易地发现这些拼写错误。没有它们,您将浪费大量时间。
关于regex - 统计词频然后排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8061459/