regex - 统计词频然后排序

标签 regex perl count words word-frequency

我正在编写一个 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/

相关文章:

linux - 将 Oracle DATE 转换为 Linux 时间

需要 SQL 查询从两个单独的表中获取信息

performance - 使用 Perl 压缩文件的最佳方法是什么?

mysql - 优化 MySQL 与许多平面文件和 HDD 利用率

mysql - 通过计数简化选择

来自具有特定值的文本文件的 C# 数组

ruby - 是否可以使这个 ruby​​ 正则表达式代码更短?

RegEx URL ReWrite 匹配表达式中的所有内容,除非术语存在

c++ - 索引文件名及其内容

python-re.findall 如何将内容分成组