【问题标题】:How can I extract numeric data from a text file?如何从文本文件中提取数字数据?
【发布时间】:2008-12-12 06:22:43
【问题描述】:

我希望 Perl 脚本从文本文件中提取数据并将其保存为另一个文本文件。文本文件的每一行都包含一个指向 jpg 的 URL,例如“http://pics1.riyaj.com/thumbs/000/082/104//small.jpg”。我希望脚本将每个 jpg URL 的最后 6 个数字(即 082104)提取到一个变量中。我希望将变量添加到新文本每一行的不同位置。

输入文字:

text http://pics1.riyaj.com/thumbs/000/082/104/small.jpg text
text http://pics1.riyaj.com/thumbs/000/569/315/small.jpg text

输出文本:

text php?id=82104 text
text php?id=569315 text 

谢谢

【问题讨论】:

  • 你自己写有什么具体问题吗?此外,URL 是否始终采用您描述的形式,或者您是否需要能够处理任意 URL?

标签: perl extract


【解决方案1】:

到目前为止,您尝试了什么?

这是一个简短的程序,可以为您提供问题的核心,您可以添加其余部分:

尽管( ) { s|http://.*/\d+/(\d+)/(\d+).*?jpg|php?id=$1$2|; 打印; }

这与使用-p 开关为您处理循环和打印的命令行程序非常接近(有关详细信息,请参阅perlrun 文档):

perl -pi.old -e 's|http://.*/\d+/(\d+)/(\d+).*?jpg|php?id=$1$2|' inputfile > outputfile

【讨论】:

    【解决方案2】:

    我不知道是根据您描述的内容(“最后 6 位数字”)回答,还是只是假设这一切都符合您展示的模式。所以我决定两种方式都回答。

    这是一种可以处理比您的示例更多样化的行的方法。

    use FileHandle;
    
    my $jpeg_RE = qr{
        (.*?)           # Anything, watching out for patterns ahead
        \s+             # At least one space
        (?> http:// )   # Once we match "http://" we're onto the next section
        \S*?            # Any non-space, watching out for what follows
        ( (?: \d+ / )*  # At least one digit, followed by a slash, any number of times
          \d+           # another group of digits
        )               # end group
        \D*?            # Any number of non-digits looking ahead
        \.jpg           # literal string '.jpg'
        \s+             # At least one space
       (.*)             # The rest of the line
    }x;
    
    my $infile  = FileHandle->new( "<$file_in" );
    my $outfile = FileHandle->new( ">$file_out" );
    
    while ( my $line = <$infile> ) { 
        my ( $pre_text, $digits, $post_text ) = ( $line =~ m/$jpeg_RE/ );
        $digits        =~ s/\D//g;
        $outfile->printf( "$pre_text php?id=%s $post_text\n", substr( $digits, -6 ));
    }
    $infile->close();
    

    但是,如果它和你展示的一样有规律,那就容易多了:

    use FileHandle;
    my $jpeg_RE = qr{
        (?> \Qhttp://pics1.riyaj.com/thumbs/\E ) 
        \d{3}
        /
        ( \d{3} )
        / 
        ( \d{3} )
        \S*?
        \.jpg
    }x;
    
    my $infile  = FileHandle->new( "<$file_in" );
    my $outfile = FileHandle->new( ">$file_out" );
    
    while ( my $line = <$infile> ) { 
        $line =~ s/$jpeg_RE/php?id=$1$2/g;
        $outfile->print( $line );
    }
    $infile->close();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多