【问题标题】:How to find number of numerical data for each and every line in a file如何查找文件中每一行的数字数据数量
【发布时间】:2016-07-15 01:41:30
【问题描述】:

请帮我计算文件每一行中的数字数据, 并找到行长。代码必须用 Perl 编写。 例如,如果我有这样一行:

INPUT:I was born on 24th october,1994.
Output:2

【问题讨论】:

  • 这里的数字数据是指1947这样的数字序列。
  • 样本输入:మోతీలాల్ నెహ్రూ (ఆంగ్లం : Motilal Nehru) (మే 6, 1861 – ఫిరబ఍రర1వ 6, 6,3) భారతీయస్వాతంత్ర్యసమరయోధుడుమరియుభారతజాతీయకాంగ్రెస్నాయకుడు。 ఇతను, బలీయమైన రాజకీయ కుటుంబ స్థాపకుడు。输出:4(8,1861,6,1931)
  • 请在问题中添加其他信息,而不是在 cmets 中。另外,这个问题也不清楚。您是否要询问行中的数字字符数?还是您要询问一行中包含的不同数字子字符串的数量?

标签: text-processing perl


【解决方案1】:

你可以这样做:

perl -ne 'BEGIN{my $x} $x += () = /[0-9]+/g; END{print($x . "\n")}' file
  • -n: 导致 Perl 在你的程序周围假设以下循环,这使得它迭代文件名参数,有点像 sed -n 或 awk:

    LINE:
      while (<>) {
          ...             # your program goes here
      }
    
  • -e:可用于进入一行程序;

  • () 将使/[0-9]+/g 在列表上下文中被评估(即() = /[0-9]+/g 将返回一个数组,其中包含在默认输入中找到的一个或多个数字的序列),而$x += 将使结果在标量中再次被评估上下文(即$x += () = /[0-9]+/g 会将在默认输入中找到的一位或多位数字的序列数添加到$x); END{print($x . "\n") 将在整个文件处理完毕后打印$x
% cat file
string 123 string 1 string string string
456 string
% perl -ne 'BEGIN{my $x} $x += () = /[0-9]+/g; END{print($x . "\n")}' file
3
% 

【讨论】:

    【解决方案2】:

    我会做这样的事情

    #!/usr/bin/perl
    
    use warnings;
    use strict;
    
    my $file = 'num.txt';
    
    open my $fh, '<', $file or die "Failed to open $file: $!\n";
    
    while (my $line = <$fh>){
        chomp $line;
        my @num = $line =~ /([0-9.]+)/g;
        print "On this line --- " .scalar(@num) . "\n";
    }
    close ($fh);
    

    我测试的输入文件--

    This should say 1
    Line 2 should say 2
    I want this line to say 5 so I have added 4 other numbers like 0.02 -1 and 5.23
    

    测试的输出----

    On this line --- 1
    On this line --- 2
    On this line --- 5
    

    使用正则表达式匹配 ([0-9.]+) 将匹配任何数字并包含任何小数(我猜你真的可以只使用 ([0-9]+) 因为你只是计算它们而不使用实际代表的数字。)

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      • 2017-05-26
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 2016-03-21
      相关资源
      最近更新 更多