tset123 发表于 2015-12-26 09:19:56

Perl处理文本一例

  在CU上看到的一个题,觉得不错,就记录下来了。原文链接在这里

  我完全是门外汉,最近有一个文档要处理,如何用perl来做?谢谢了
一个文本文件里有多行如下,数量不定
Lif(__amscript_cd("www.xizi.com")){__amscript_wc('#closead {display:none;}');};
Lif(__amscript_cd("www.xizi.com")){__amscript_wc('#footer_win {display:none;}');};
Lif(__amscript_cd("www.xizi.com")){__amscript_wc('.mainad {display:none;}');};
Lif(__amscript_cd("www.xizi.com")){__amscript_wc('.mt5.recommend {display:none;}');};
Lif(__amscript_cd("gougou.com")){__amscript_wc('.ggAD {display:none;}');};
Lif(__amscript_cd("gougou.com")){__amscript_wc('.ggSideBox {display:none;}');};
…………
要合并为如下
Lif(__amscript_cd("www.xizi.com")){__amscript_wc('#closead, #footer_win, .mainad, .mt5.recommend {display:none;}');};
Lif(__amscript_cd("gougou.com")){__amscript_wc('.ggAD, .ggSideBox {display:none;}');};

  思路,可以将url视为key,而将合并的字符串视为value,这样存储下来,在打印即可。只是打印的时候有点麻烦,因为这个字符串里面包含了单引号,双引号,小括弧和花括弧,用q##做为字符串界定符即可。
  代码如下



use strict;
use warnings;
sub test {
    my %comments_of_url = ();
    open FILE, "<D:/Codesnippets/Perl/abc.txt" or die $!;
    while (<FILE>) {
      # Skip empty lines
      next if /^\s*$/;
      # Use url as key and #xxx as value for each line
      # Merge all the #xxx for a url
      if (/amscript_cd\("(.*?)"\)\){__amscript_wc\('(.*?)\s+\{/) {
            $comments_of_url{ $1 } .= ( $2 . ',' );
      }            
    }
    foreach my $key (keys %comments_of_url) {
      chomp (my $value = $comments_of_url{$key});
      print q{Lif(__amscript_cd("};
      print $key;
      print q#")){__amscript_wc('#;
      print $value;
      print q#{display:none;}');};#;
      print "\n";
    }
}
sub main {
    &test();
}
&main();
1
  ==
页: [1]
查看完整版本: Perl处理文本一例