获取使用Perl写入CSV的结果 [英] Get results to write to CSV using Perl

查看:71
本文介绍了获取使用Perl写入CSV的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下Perl脚本会可靠地读取html文件并剥离我不需要的内容.它还打开一个空白的csv文档.
我的问题是,我想使用名称"作为字段1将精简结果导入CSV的3个字段中,作为字段2居住,并作为字段3进行注释.
结果将显示在cmd提示中,而不显示在CSV中.

The following Perl script cureently reads in an html file and strips off what I don''t need. It also opens up a csv document which is blank.
My problem being is I want to import the stripped down results into the CSV''s 3 fields using Name as field 1, Lives in as field 2 and commented as field 3.
The results are getting displayed in the cmd prompt but not in the CSV.

use warnings; 
use strict;  
use DBI;
use HTML::TreeBuilder;  
use Text::CSV;
open (FILE, ''punter.htm''); 
#open (my $fh, ">punter.csv") || die "couldn''t open the file!";

 my $csv = Text::CSV->new (); 
 
$csv->column_names(''field1'', ''field2'', ''field3''); 
open my $fh, ">", "punter.csv" or die "new.csv $!"; 
while ( my $l = $csv->getline_hr(my $fh)) { 
    next if ($l->{''field1''} =~ /xxx/); 
    printf "Field1: %s Field2: %s Field3: %s\n", $l->{''field1''}, $l->{''field2''}, $1->{''field3''}; 
$csv->print (my $fh, [my $name, my $location, my $comment]);
} 
close my $fh1 or die "$!"; 
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的示例是-



An example of the html is -

<pre lang="xml"><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>







How can I get the results into a CSV?

推荐答案

fh,> punter.csv")||死于无法打开文件!"; my
fh, ">punter.csv") || die "couldn''t open the file!"; my


csv =文本:: CSV-> new();
csv = Text::CSV->new ();


csv-> column_names(''field1'','' field2'',``field3''); 打开我的
csv->column_names(''field1'', ''field2'', ''field3''); open my


这篇关于获取使用Perl写入CSV的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆