【问题标题】:Several Pattern extract from multiple CSV files从多个 CSV 文件中提取多个模式
【发布时间】:2020-11-30 18:49:08
【问题描述】:

我是编程新手,我想在 perl 中为以下函数编写代码。

我有几个 CSV 文件(1.csv、2.csv、3.csv、4.csv、.....),每个 csv 文件中的行如下所示:

<time, id1, id2, id3, filename> :

202008110100,10819066580072,2147858602,,Afile.txt
202008110110,12819066589761,,AC987678,Bfile.txt
202008110120,,8927489178,AC398761,Bfile.txt
202008110130,29274125780232,3829271910,AC119651,Cfile.txt
.
.
.
#id1,id2,id3 might be blank sometimes.

我有这样的输入:

<starttime,endtime,id1,id2,id3>:
#id1,id2,id3 might be **0**
eg):202008110105,202008110115,0,2147858602,0

如果id1,id2,id3 = 0,忽略该值,只匹配非零id

并在starttimeendtime期间提取time

我期待这样的匹配输出:

1.csv:Afile.txt

以下是我写的,但似乎有问题...有人可以帮助我吗?

my $dir = <C:/Windows/Users/USER/Documents/Perlprogram>;
@files = ("1.csv","2.csv, 3.csv, 4.csv");

foreach $file (@files) {        
print "$file\n" if -f $file;
open(IN, "<./$file") or die("Error");
@before = <IN>;
close(IN);

@after = grep(/$greplist/, @before);
foreach $after (@after) {
print "$after\n";
}
sub after {
    $time = $_[6];
    if ($time >= $starttime and $time <=$endtime){
        open(OUT, ">>./search_result.txt");
        print($file,$_[4]);
        print(OUT $_[4]);
        close(OUT);
    }
}           

【问题讨论】:

  • 输入数据从何而来?文件,标准输入或其他?重写您的问题以澄清您尝试实现的目标。如果您不在代码中使用 $dir 变量,它有什么用?如果您从文件中读取数据,则给出文件中显示的数据样本。
  • 欢迎使用 Stack Overflow 和 Perl 标签。请edit您的问题并包括您现在收到的输出或错误消息。还要解释是否有不同的文件很重要。您是否需要同时与其中几个互动?如果不是,则该信息与您的问题无关。那些身份证呢?如果三个 ID 中的任何一个是 0,您要忽略该行吗?那么$dir呢?该变量未在您的代码中使用。
  • 你在哪里定义$greplist?你在哪里调用子程序after()?以use strict; use warnings; 开始您的代码,perl 将帮助您消除很多错误。
  • 我认为您错过了第一个 foreach 循环的结束 }

标签: csv perl


【解决方案1】:

好像有什么问题……

@files = ("1.csv","2.csv, 3.csv, 4.csv");

除了语法之外,第一个之后的文件名没有正确引用。

正如北极熊所说,$greplist 没有定义。假设它设置为您所说的 input,我们可以使用

获取各个字段
($starttime,$endtime,$id1,$id2,$id3) = split ',', $greplist;

程序的其余部分有些不连贯;您可以将@before = &lt;IN&gt;; 行替换为

    while (<IN>)
    {
        @_ = split ','; # split the CSV line to the values
        print $_[4] if  !$id1 || $_[1] == $id1
                    and !$id2 || $_[2] == $id2
                    and !$id3 || $_[3] == $id3
                    and $starttime <= $_[0]
                    and $_[0] <= $endtime
    }

并删除 foreach $file 循环的其他内容。

【讨论】:

    猜你喜欢
    • 2017-12-15
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 2017-01-12
    • 1970-01-01
    • 2016-12-29
    相关资源
    最近更新 更多