2011-11-09 117 views
2

我正在写一个perl脚本,其中a应该处理文本,然后向词典提供词频,然后对词典进行排序。该文本是Edgar Poe的“Golden Bug”的摘录,目的是计算所有单词的频率。但我做错了,因为我没有输出。我什么时候做错了?谢谢。计算单词频率,然后对它们进行排序

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; 
} 
} 
+0

你能发布一个小单词列表吗?您还没有在任何地方声明%dictionary ... –

回答

4

你在你的代码:

@word=split(/ /); 
foreach $word (@words) 
    { 

您已经命名分割在阵列@word但您使用的是阵列@words在for循环。

@word=split(/ /); 

应该

@words=split(/ /); 

另一个错字在byDescendingValues常规:

$value=$dictionaty{$b} <=> $dictionary{$a}; 
       ^^ 

正如在其他答案建议,你真的应该添加

use strict; 
use warnings; 

使用这些你合作很容易发现这些错别字。没有他们,你会浪费你很多时间。

+0

但是如何正确地对单词进行排序? –

+0

@VovaStajilov:我已经更新了答案。 – codaddict

2

以及令人困惑的@word和@words,你也使用$ dictionaty而不是$字典。这是明智的

use strict; 
use warnings; 

在你的程序的启动和使用my声明所有的变量。这样一些微不足道的错误就由Perl自己修复了。

+0

严格地说,这些错误是突出显示的,而不是固定的 – Zaid

相关问题