加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

如何使用Perl从大文件中删除非唯一行?

发布时间:2020-12-16 06:08:50 所属栏目:大数据 来源:网络整理
导读:使用Perl通过 Windows中的批处理文件调用重复数据删除 Windows中的DOS窗口通过批处理文件调用. 批处理文件调用执行操作的Perl脚本.我有批处理文件. 只要数据文件不是太大,我工作的代码脚本就会删除重复数据. 需要解决的问题是数据文件较大(2 GB或更多),在此
使用Perl通过 Windows中的批处理文件调用重复数据删除
Windows中的DOS窗口通过批处理文件调用.
批处理文件调用执行操作的Perl脚本.我有批处理文件.
只要数据文件不是太大,我工作的代码脚本就会删除重复数据.
需要解决的问题是数据文件较大(2 GB或更多),在此文件大小时,尝试将完整文件加载到阵列中以便删除重复数据时会发生内存错误.
在以下子程序中发生内存错误: –

@contents_of_the_file = <INFILE>;

(一种完全不同的方法是可以接受的,只要它解决了这个问题,请建议).
子程序是: –

sub remove_duplicate_data_and_file
{
 open(INFILE,"<" . $output_working_directory . $output_working_filename) or dienice ("Can't open $output_working_filename : INFILE :$!");
  if ($test ne "YES")
   {
    flock(INFILE,1);
   }
  @contents_of_the_file = <INFILE>;
  if ($test ne "YES")
   {
    flock(INFILE,8);
   }
 close (INFILE);
### TEST print "$#contents_of_the_filenn";
 @unique_contents_of_the_file= grep(!$unique_contents_of_the_file{$_}++,@contents_of_the_file);

 open(OUTFILE,">" . $output_restore_split_filename) or dienice ("Can't open $output_restore_split_filename : OUTFILE :$!");
 if ($test ne "YES")
  {
   flock(OUTFILE,1);
  }
for($element_number=0;$element_number<=$#unique_contents_of_the_file;$element_number++)
  {
   print OUTFILE "$unique_contents_of_the_file[$element_number]n";
  }
 if ($test ne "YES")
  {
   flock(OUTFILE,8);
  }
}

解决方法

您不必要地在@contents_of_the_file中存储原始文件的完整副本,并且 – 如果复制量相对于文件大小较低 – 在%unique_contents_of_the_file和@unique_contents_of_the_file中几乎有两个其他完整副本.正如ire_and_curses所指出的,你可以通过对数据进行两次传递来减少存储需求:(1)分析文件,存储有关非重复行的行号的信息; (2)再次处理文件以将非重复写入输出文件.

这是一个例子.我不知道我是否选择了散列函数的最佳模块(Digest::MD5);也许其他人会对此发表评论.还要注意你应该使用的open参数的3参数形式.

use strict;
use warnings;

use Digest::MD5 qw(md5);

my (%seen,%keep_line_nums);
my $in_file  = 'data.dat';
my $out_file = 'data_no_dups.dat';

open (my $in_handle,'<',$in_file) or die $!;
open (my $out_handle,'>',$out_file) or die $!;

while ( defined(my $line = <$in_handle>) ){
    my $hashed_line = md5($line);
    $keep_line_nums{$.} = 1 unless $seen{$hashed_line};
    $seen{$hashed_line} = 1;
}

seek $in_handle,0;
$. = 0;
while ( defined(my $line = <$in_handle>) ){
    print $out_handle $line if $keep_line_nums{$.};
}    

close $in_handle;
close $out_handle;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读