2012-06-24 14 views
7

Ho una lista di numeri interi - esiste una libreria per convertirli in classifica in testo semplice? IE: 1,2,3 -> "primo, secondo, terzo"?C'è una libreria per convertire l'intero in primo/secondo/terzo

+1

http://www.daniweb.com/software-development/python/code/216839/number-to-word-converter-python –

+1

All'inizio dell'università è stato uno dei nostri compiti il ​​primo giorno a scrivere esattamente questo Giava. Se hai un po 'di esperienza nella programmazione, non dovresti impiegare più di 30 minuti. –

+1

30 minuti? davvero lol .. intendi 1 minuto .... http://jsfiddle.net/cmvLS/ (javascript) – ncubica

risposta

5

Quanto in alto stai andando? (Ti capita mai aspettate più alto rispetto, ad esempio, "XX"?)

Forse hai solo bisogno di un dict,

nth = { 
    1: "first", 
    2: "second", 
    3: "third", 
    4: "fourth" 
    # etc 
} 
+3

Diventa solo più facile dopo "ventesimo" :) –

2

A seconda della situazione, si potrebbe trovare utile per mantenere l'intero e append " st "," nd "," rd "e" th ". In tal caso, ecco un semplice algoritmo:

NOTA: questo algoritmo è scritto in Java. Non conosco Python. Chiunque voglia riscriverlo in Python, sii mio ospite.

public static String appendInt(int number) { 
    String value = String.valueOf(number); 
    if(value.length() > 1) { 
     // Check for special case: 11 - 13 are all "th". 
     // So if the second to last digit is 1, it is "th". 
     char secondToLastDigit = value.charAt(value.length()-2); 
     if(secondToLastDigit == '1') 
      return "th"; 
    } 
    char lastDigit = value.charAt(value.length()-1); 
    switch(lastDigit) { 
     case '1': 
      return "st"; 
     case '2': 
      return "nd"; 
     case '3': 
      return "rd"; 
     default: 
      return "th"; 
    } 
} 

Così

System.out.println(1 + appendInt(1)); 
System.out.println(2 + appendInt(2)); 
System.out.println(3 + appendInt(3)); 
System.out.println(4 + appendInt(4)); 
System.out.println(5 + appendInt(5)); 
System.out.println(11 + appendInt(11)); 
System.out.println(21 + appendInt(21)); 

display

1st 
2nd 
3rd 
4th 
5th 
11th 
21st 
+0

Questo è un modo fantastico per farlo. – answerSeeker

3

non posso commentare il post di ryvantage a causa di punti, ma ho scritto lo stesso codice per Python:

def appendInt(num): 
    if num > 9: 
     secondToLastDigit = str(num)[-2] 
     if secondToLastDigit == '1': 
      return 'th' 
    lastDigit = num % 10 
    if (lastDigit == 1): 
     return 'st' 
    elif (lastDigit == 2): 
     return 'nd' 
    elif (lastDigit == 3): 
     return 'rd' 
    else: 
     return 'th' 



def appendInt2(num): 
    value = str(num) 
    if len(value) > 1: 
     secondToLastDigit = value[-2] 
     if secondToLastDigit == '1': 
      return 'th' 
    lastDigit = value[-1] 
    if (lastDigit == '1'): 
     return 'st' 
    elif (lastDigit == '2'): 
     return 'nd' 
    elif (lastDigit == '3'): 
     return 'rd' 
    else: 
     return 'th' 

Il il secondo è più di un trans diretto mento, ma ho trovato che la prima variante è notevolmente più veloce:

Ven 28 Ago 2015 11:48:13 risultati

  300000005 function calls in 151.561 seconds 

    Ordered by: call count, name/file/line 

    ncalls tottime percall cumtime percall filename:lineno(function) 
100000000 6.674 0.000 6.674 0.000 {len} 
100000000 43.064 0.000 43.064 0.000 test.py:7(appendInt) 
100000000 66.664 0.000 73.339 0.000 test.py:22(appendInt2) 
     1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 
     1 0.000 0.000 151.561 151.561 <string>:1(<module>) 
     1 0.000 0.000 151.561 151.561 test.py:51(main) 
     1 16.737 16.737 59.801 59.801 test.py:39(test1) 
     1 18.421 18.421 91.759 91.759 test.py:45(test2) 
+0

array [-2] è il penultimo valore dell'array in Python? * cool * – ryvantage

2

Analogamente alla vena @Hugh Bothwellwas following, solo non si utilizza un dict (dalla tua chiavi sono già bello e numerica), ho messo insieme il seguente "uno di linea":

ordinal=lambda x:["first","second","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth"][x-1] 

che copre tutti i casi fino a 12. Se y Hai bisogno di un livello più alto (in centinaia, ecc.), quindi probabilmente avrai bisogno di qualcosa di più robusto (con ricorsione immaginerei, ecc.).

0

Una piacevole e semplice riscrittura:

def num_to_ith(num): 
    """1 becomes 1st, 2 becomes 2nd, etc.""" 
    value    = str(num) 
    before_last_digit = value[-2] 
    last_digit  = value[-1] 
    if len(value) > 1 and before_last_digit == '1': return value +'th' 
    if last_digit == '1': return value + 'st' 
    if last_digit == '2': return value + 'nd' 
    if last_digit == '3': return value + 'rd' 
    return value + 'th' 
9

Il pacchetto pitone inflect ha un metodo per convertire numeri in ordinali:

import inflect 
p = inflect.engine() 

for i in range(1,25,5): 
    print(p.ordinal(i)) 

display:

1st 
6th 
11th 
16th 
21st 
+1

Haha, fantastico! Questo ** È ** la risposta corretta alla domanda. – Atcold

+0

Wow che quello che stavo cercando !! – answerSeeker

+0

'p.number_to_words (p.ordinal (i))' lo mostrerà come 'first',' second', 'third', ecc. –

0

mio codice per questo utilizza la lista, il modulo intero per trovare la prima cifra e la divisione del piano intero per verificare la presenza di ru Le 11 a 13.

def stringify(number): 
     suffix = ["th","st","nd","rd","th","th","th","th","th","th"] 
     return str(number) + suffix[number % 10] if str(number // 10)[-1] != 1 else str(number) + "th"   

L'ultima riga più leggibile:

if str(number // 10)[-1] != '1':  
     return str(number) + suffix[number % 10] 
    else: 
     return str(number) + "th" 

In sostanza, sto controllando la seconda cifra per 1 *, che indica un possibile 11, 12, interruttore di regola 13.Per i detentori delle regole, la lista fa riferimento al resto di una divisione per 10 (operatore modulo).

Non ho eseguito alcun test per l'efficienza del codice e la verifica rispetto alla lunghezza è molto più leggibile, ma funziona.

* (str (numero) [- 2]. Genera un IndexError se l'ingresso è una singola cifra Uso divisione piano su interi provoca sempre almeno 1 cifra così la stringa avrà sempre un -1 indice)

Problemi correlati