以下Perl脚本会在html文件中读取并删除我不需要的内容。它还会打开一个空白的csv文档。
我的问题是我想将精简结果导入CSV的3个字段,使用名称作为字段1,生活在字段2中并注释为字段3.
结果显示在cmd提示符中,但不显示在CSV中。
use warnings;
use strict;
use DBI;
use HTML::TreeBuilder;
use Text::CSV;
open (FILE, 'file.htm');
open (F1, ">file.csv") || die "couldn't open the file!";
my $csv = Text::CSV->new ({ binary => 1, empty_is_undef => 1 })
or die "Cannot use CSV: ".Text::CSV->error_diag ();
open my $fh, "<", 'file.csv' or die "ERROR: $!";
$csv->column_names('field1', 'field2', 'field3');
while ( my $l = $csv->getline_hr($fh)) {
next if ($l->{'field1'} =~ /xxx/);
printf "Field1: %s Field2: %s Field3: %s\n",
$l->{'field1'}, $l->{'field2'}, $1->{'field3'}
}
close $fh;
my $tree = HTML::TreeBuilder->new_from_content( do { local $/; <FILE> } );
for ( $tree->look_down( 'class' => 'postbody' ) ) {
my $location = $_->look_down
( 'class' => 'posthilit' )->as_trimmed_text;
my $comment = $_->look_down( 'class' => 'content' )->as_trimmed_text;
my $name = $_->look_down( '_tag' => 'h3' )->as_text;
$name =~ s/^Re:\s*//;
$name =~ s/\s*$location\s*$//;
print "Name: $name\nLives in: $location\nCommented: $comment\n";
}
html的一个例子是:
<div class="postbody">
<h3><a href "foo">Re: John Smith <span class="posthilit">England</span></a></h3>
<div class="content">Is C# better than Visula Basic?</div>
</div>
答案 0 :(得分:10)
您实际上没有向CSV文件写任何内容。首先,不清楚为什么要打开文件进行写入然后再阅读。然后从(现在为空)文件中读取。然后,您从HTML中读取,并显示您想要的内容。
如果您想要在其中显示数据,您肯定需要在某处写入CSV文件!
此外,如果您想通过Text :: CSV使用它们,最好避免使用文件句柄的裸字。
也许你需要这样的东西:
my $csv = Text::CSV->new();
$csv->column_names('field1', 'field2', 'field3');
open $fh, ">", "file.csv" or die "new.csv: $!";
...
# As you handle the HTML
$csv->print ($fh, [$name, $location, $comment]);
...
close $fh or die "$!";