2

我有以下代码

chdir("c:/perl/normalized");
$docid=0;
my %hash = ();
@files = <*>;
foreach $file (@files) 
  {
    $docid++;
    open (input, $file);    
    while (<input>) 
      {
    open (output,'>>c:/perl/tokens/total');
    chomp;
    (@words) = split(" ");  
    foreach $word (@words)
    {
    push @{ $hash{$word} }, $docid;

    }
      }
   }
foreach $key (sort keys %hash) {
    print output"$key : @{ $hash{$key} }\n";
}


close (input);
close (output);

这是文件中的示例输出

of : 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 3 3 4 4 4 4 5 6 6 7 7 7 7 7 7 7 7 7

这是真的,因为例如“of”一词在第一个文档中存在 10(十个)次,但是有没有办法删除重复的值;即而不是十个我只想要一个谢谢你的帮助

4

1 回答 1

5

为避免一开始就添加副本,请更改

foreach $word (@words)

foreach $word (uniq @words)

如果您想将 dups 留在数据结构中,请改为更改

print output"$key : @{ $hash{$key} }\n";

print output "$key : ", join(" ", uniq @{ $hash{$key} }), "\n";

uniq由 List::MoreUtils 提供。

use List::MoreUtils qw( uniq );

或者你可以使用

sub uniq { my %seen; grep !$seen{$_}++, @_ }
于 2012-11-06T19:07:05.707 回答