Search code examples
rnlpuser-inputstdintext-mining

R: Select option by introducing a number


I would like to build a very simple, sketchy, function where you can introduce a word (in Spanish) and get the most feasible next word (kind of a text predictor). So when the user introduces me, suggestions are ha, he, lo, da and gusta. Now, I would like to enable the user to select one of those five suggestions by typing 1, 2, 3, 4, or 5. Is there any way to do this in R?

predictor<-function(){
  word<-readLines(stdin(),n=1)
  words<-sort(table[first==word],decreasing=TRUE)[2:6]
  suggestions<-gsub(".* ","",names(words))
  return(suggestions)
}

#table = table with unigram and bigram frequencies of a corpus
#first = vector with the first word in each bigram

> predictor()
me
[1] "ha"    "he"    "lo"    "da"    "gusta"

Solution

  • You already prompt for user input once. You can do it again to get the number of the item you want to get. But you'll have to print the suggestions in a way that allows the user to choose.

    predictor = function(){
      ### Since I have neither the table nor the list, I just made a makeshift words vector
      words = c("ha","he","lo","da","gusta")
      names(words)=words
      
      suggestions<-paste(1:length(words),names(words),sep=": ")
      print(paste("Possible Words:",paste(suggestions,collapse="; ")))
      print("Please enter a number to select:")
      #input = scan("",what="character",n=1)
      input<-readLines(stdin(),n=1)
      print(paste("You selected Item #",input,": ",names(words)[as.integer(input)],sep=""))
    }
    
    

    This will give you the output:

    [1] "Possible Words: 1: ha; 2: he; 3: lo; 4: da; 5: gusta"
    [1] "Please enter a number to select:"
    4
    [1] "You selected Item #4: da"