搜索,并从CSV文件中删除列 [英] Search for, and remove column from CSV file

查看:187
本文介绍了搜索,并从CSV文件中删除列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个子程序,将采取两个参数,一个文件名列名内一个CSV文件。子程序将搜索的第二个参数(列名),并从CSV文件中删除该列(或列),然后返回CSV去除参数文件。

I'm trying to write a subroutine that will take two arguments, a filename and the column name inside a CSV file. The subroutine will search for the second argument (column name) and remove that column (or columns) from the CSV file and then return the CSV file with the arguments removed.

我觉得我已经通过这个子上半年得到(打开文件,检索头和值),但我似乎无法找到一种方法来搜索CSV文件的字符串用户输入并删除整列。有任何想法吗?这里是我到目前为止所。

I feel like I've gotten through the first half of this sub (opening the file, retrieve the headers and values) but I can't seem to find a way to search the CSV file for the string that the user inputs and delete that whole column. Any ideas? Here's what I have so far.

sub remove_columns {
   my @Para = @_;
   my $args = @Para;
   die "Insufficent arguments\n" if ($nargs < 2);

   open file, $file
   $header = <file>;
   chomp $header;

   my @hdr = split ',',$header;

   while (my $line = <file>){
    chomp $line;
    my @vals = split ',',$line;

    #hash that will allow me to access column name and values quickly
    my %h;

    for (my $i=0; $i<=$#hdr;$i++){
      $h{$hdr[$i]}=$i;
    }
     ....
}

在此处,搜索和删除将完成。我一直在思考如何去了解这一点;我会修改CSV文件,将是巨大的,所以速度是一个因素,但我似乎无法想出一个好办法去了解这一点。我是新来的Perl,所以我挣扎了一下。

Here's where the search and removal will be done. I've been thinking about how to go about this; the CSV files that I'll be modifying will be huge, so speed is a factor, but I can't seem to think of a good way to go about this. I'm new to Perl, so I'm struggling a bit.

推荐答案

有是优雅的方式如何从数组中删除某些列。如果我有列在阵列去除 @cols ,而在 @headers 我可以做索引,以$阵头p $ pserve:

There is elegant way how to remove some columns from array. If I have columns to removal in array @cols, and headers in @headers I can make array of indexes to preserve:

my %to_delete;
@to_delete{@cols} = ();
my @idxs = grep !exists $to_delete{$headers[$_]}, 0 .. $#headers;

然后,它很容易使新标题

Then it's easy to make new headers

@headers[@idxs]

和也读列新行

@columns[@idxs]

同样的方法可以用于例如用于重排阵列。这是非常快速和pretty惯用的Perl的路该怎么做这样的任务。

The same approach can be used for example for rearranging arrays. It is very fast and pretty idiomatic Perl way how to do this sort of tasks.

这篇关于搜索,并从CSV文件中删除列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆