【问题标题】:Get results to write to CSV using Perl使用 Perl 将结果写入 CSV
【发布时间】:2011-09-30 11:09:27
【问题描述】:

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

【问题讨论】:

    标签: html perl csv writetofile


    【解决方案1】:

    您实际上并没有向 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 "$!";
    

    【讨论】:

      猜你喜欢
      • 2020-03-16
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 2015-02-18
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多