0

下面的 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>
4

1 回答 1

10

您实际上并没有向 CSV 文件写入任何内容。首先,不清楚为什么要打开文件进行写入,然后再打开文件进行读取。然后,您从(现在为空的)文件中读取。然后你从 HTML 中读取,并显示你想要的内容。

如果您希望数据出现在 CSV 文件中,您肯定需要在某处写入该文件!

Also, it's best to avoid barewords for file handles if you want to use them through Text::CSV.

Maybe you need something like:

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 "$!";
于 2011-07-07T13:31:42.473 回答