我有一种csv文件,带有一些额外的参数。我不想写自己的解析器,因为我知道那里有很多好的解析器。问题是,如果有任何解析器可以处理我的场景,我就不清楚了。 我的csv文件如下所示:
我想首先阅读#ADM下面的第二行,所以在这种情况下有3行。我想在#Prov之后阅读第二行。
是否有任何好的解析器或读者可以使用它来帮助我解决这个问题,我将如何编写以处理我的场景?
我的文件扩展名也不是.csv,它是.lab,但我想那不会有问题吗?
答案 0 :(得分:0)
前,我没有看到任务的特定语言,并且对c#
的阅读太晚了。这是一个perl
解决方案,但评论很好,所以我希望它可以很有用,也很容易翻译成其他语言。
假设测试文件(infile
)如:
1
2
3
4
5
#Adm
6
7
#Prov
8
9
#Adm
10
11
#Prov
12
13
#Adm
14
15
#Prov
16
17
script.pl
的内容:
use warnings;
use strict;
## Assign empty value to read file by paragraphs.
$/ = qq[];
## Arrays to save second row of its section.
my (@adm, @prov);
## Regex to match beginning of section.
my $regex = qr/(?:#(?|(Adm)|(Prov)))/;
## Read file.
while ( <> ) {
## Remove last '\n'.
chomp;
## If matches the section and it has at least two lines...
if ( m/\A${regex}/ and tr/\n/\n/ == 2 ) {
## Group the section name ($1) and its second line ($2).
if ( m/\A${regex}.*\n^(.*)\Z/ms ) {
## Save line in an array depending of section's value.
if ( $1 eq q[Adm] ) {
push @adm, $2;
}
elsif ( $1 eq q[Prov] ) {
push @prov, $2;
}
}
}
}
## Print first lines of 'Adm' section and later lines of 'Prov' section.
for ( ( @adm, @prov ) ) {
printf qq[%s\n], $_;
}
exit 0;
像以下一样运行:
perl script.pl infile
使用以下输出:
7
11
15
9
13
17