2013-04-03 23 views
1

在此之前,我已經提出了同樣的問題,我得到了答案,但我錯了。我需要將數字轉換爲單詞而不使用任何庫,特別是Lingua :: Numbers。Perl將數字更改爲單詞

我找到了一個例子來分隔電話號碼中的數字。然後我試着在腳本中實現這個例子。但它沒有奏效。

這是我的腳本。

$x = "1104"; 
$x =~ s/1/ one /gi; #from 1-10, I, substitute number to words to words 
$x =~ s/2/ two /gi; 
$x =~ s/3/ three /gi; 
$x =~ s/4/ four /gi; 
$x =~ s/5/ five /gi; 
$x =~ s/6/ six /gi; 
$x =~ s/7/ seven /gi; 
$x =~ s/8/ eight /gi; 
$x =~ s/9/ nine /gi; 
$x =~ s/10/ ten /gi; 
$y = ($x{1}[thousand]?$x{1}[hundred and]?$x{2}); 


    #then I will insert all my $x into $y. 

$x =~ s/$x/$y/gi; #Here i substitute again to change all number to words 

#that is my idea. 

print "$x"; 

我試着讓它的第一個4位數。如果成功,我可以繼續插入,直到有7-8個數字或更多。

+0

爲什麼不查找庫的實現並複製你需要的部分? –

+0

它看起來不像可以由正則表達式處理的東西(至少不容易)。在代碼中做它會容易得多。還要注意11-19(例如十八)和(1-9)* 10(例如二十或三十)也需要單獨規定。 – Dukeling

+0

好的,從技術上來說只有11-13,15和(1-3,5)* 10是不同的。 – Dukeling

回答

1

在代碼中執行此操作更直觀。這是在C#中開始,但應該只需要最少的變化,工作的幾乎所有的類C語言:

string Speak(int num) 
{ 
    if (num < 0) return "negative " + Speak(-num); 
    if (num >= 1000000000) return Speak(num/1000000000) + " billion " + Speak(num % 1000000000); 
    if (num >= 1000000) return Speak(num/1000000) + " million " + Speak(num % 1000000); 
    if (num >= 1000) return Speak(num/1000) + " thousand " + Speak(num % 1000); 
    if (num >= 100) return Speak(num/100) + " hundred " + Speak(num % 100); 
    if (num >= 20) 
    { 
     switch (num/10) 
     { 
      case 2: return "twenty " + Speak(num % 10); 
      case 3: return "thirty " + Speak(num % 10); 
      case 4: return "forty " + Speak(num % 10); 
      case 5: return "fifty " + Speak(num % 10); 
      case 6: return "sixty " + Speak(num % 10); 
      case 7: return "seventy " + Speak(num % 10); 
      case 8: return "eighty " + Speak(num % 10); 
      case 9: return "ninety " + Speak(num % 10); 
     } 
    } 
    switch (num) 
    { 
     case 0: return ""; 
     case 1: return "one"; 
     case 2: return "two"; 
     case 3: return "three"; 
     case 4: return "four"; 
     case 5: return "five"; 
     case 6: return "six"; 
     case 7: return "seven"; 
     case 8: return "eight"; 
     case 9: return "nine"; 
     case 10: return "ten"; 
     case 11: return "eleven"; 
     case 12: return "twelve"; 
     case 13: return "thirteen"; 
     case 14: return "fourteen"; 
     case 15: return "fifteen"; 
     case 16: return "sixteen"; 
     case 17: return "seventeen"; 
     case 18: return "eighteen"; 
     case 19: return "nineteen"; 
    } 
    return ""; 
} 

例子:

Speak("123000701") -> "one hundred twenty three million seven hundred one"; 

我會離開它作爲一個練習添加支持零,逗號和「和」字。