R package to convert numbers to full-text number

Asked

Viewed 369 times

2

I am looking for an R package that converts a number to the number written in full. The functionality would be, for example, "134" = "cento e trinta e quatro".

Does anyone know?

1 answer

3


As far as I know, there is nothing ready, but as the rules are simple it is not difficult to program.

You need a few-stop:

excessoes <- data.frame(
  num = 11:19,
  nome = c("onze", "doze", "treze", "catorze", "quinze", "dezesseis", "dezessete", "dezoito", "dezenove"),
  stringsAsFactors = F
)

unidades <- data.frame(
  num = 1:9,
  nome = c("um", "dois", "três", "quatro", "cinco", "seis", "sete", "oito", "nove"),
  stringsAsFactors = F
)  

dezenas <- data.frame(
  num = 1:9,
  nome = c("dez", "vinte", "trinta", "quarenta", "cinquenta", "sessenta", "setenta", "oitenta", "noventa"),
  stringsAsFactors = F
)

Followed by a function that joins according to the rules of numerals.

library(stringr)
escrever_numero <- function(x){

  tamanho <- str_length(x)
  num_vetor <- unlist(str_split(x, ""))

  if(x %in% excessoes$num){
    return(excessoes$nome[excessoes$num == x])
  } else {
    unidade <- num_vetor[tamanho]
    unidade <- unidades$nome[unidades$num == unidade]
    if(tamanho > 1){
      dezena <- num_vetor[tamanho -1]
      dezena <- dezenas$nome[dezenas$num == dezena]
    }
  }

  if(length(unidade) == 0){
    return(dezena)
  } else if (tamanho > 1){
    return(paste(dezena, "e", unidade))
  } else{
    paste(unidade)
  }

}

I made a function quickly, it works p/numbers from 1 to 99. But if you understand the logic it is easy to expand to more numbers.

> escrever_numero(81)
[1] "oitenta e um"
> escrever_numero(99)
[1] "noventa e nove"
> escrever_numero(1)
[1] "um"
> escrever_numero(10)
[1] "dez"
> escrever_numero(15)
[1] "quinze"

It’s not very elegant, but it might help...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.