【问题标题】:How can I convert a number to text in Perl?如何在 Perl 中将数字转换为文本?
【发布时间】:2010-11-20 12:47:09
【问题描述】:

我的程序中需要一些代码,它将数字作为输入并将其转换为相应的文本,例如745到“七百四十五”。

现在,我可以为此编写代码,但是我可以使用任何库或现有代码吗?

【问题讨论】:

标签: perl numbers


【解决方案1】:

来自Lingua::EN::Numbers的perldoc:

use Lingua::EN::Numbers qw(num2en num2en_ordinal);

my $x = 234;
my $y = 54;
print "You have ", num2en($x), " things to do today!\n";
print "You will stop caring after the ", num2en_ordinal($y), ".\n";

打印:

You have two hundred and thirty-four things to do today!
You will stop caring after the fifty-fourth.

【讨论】:

    【解决方案2】:

    你需要看this stackoverflow question

    来自上述链接:

    perl -MNumber::Spell -e 'print spell_number(2);'
    

    【讨论】:

      【解决方案3】:

      看看Math::BigInt::Named 模块。

      【讨论】:

        【解决方案4】:

        你可以试试这样的:

        #!/usr/bin/perl
        
        use strict;
        use warnings;
        
        my %numinwrd = (
          0 => 'Zero', 1 => 'One', 2 => 'Two',   3 => 'Three', 4 => 'Four',
          5 => 'Five', 6 => 'Six', 7 => 'Seven', 8 => 'Eight', 9 => 'Nine',
        );
        
        print "The number when converted to words is 745=>".numtowrd(745)."\n";
        
        sub numtowrd {
          my $num = shift;
          my $txt = "";  
          my @val = $num =~ m/./g;
        
          foreach my $digit (@val) {    
            $txt .= $numinwrd{$digit} . " ";   
          }
        
          return $txt;
        }
        

        输出是:

        The number when converted to words is 745=>Seven Four Five 
        

        【讨论】:

        • 要将@val 转换为$txt,使用$txt = join " ", map {$numinwrd{$_}} @val 可能更容易,从而有效地使您的子成为单线。此外,此解决方案不会产生 seven hundred forty five
        • 如果能输出到七百四十五可以给代码
        【解决方案5】:

        也可以看看Nums2Words

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-11-19
          • 2019-10-21
          • 2015-05-13
          • 1970-01-01
          • 2012-05-21
          • 2016-12-03
          • 1970-01-01
          相关资源
          最近更新 更多