R/emotion.R

Defines functions emotion

Documented in emotion

#' R interface to tencent AI lab's emotion analysis
#'
#' \code{emotion} returns the results  of emotion analysis
#' @param text The text is sent to API
#' @param app_key Your app key
#' @param app_id Your app ID
#' @return positive = 1, neuter = 0, nagetive = -1
#' @author Ao Sun <\url{https://ao-sun.github.io/}>
#' @description text can only be Chinese, this function performs poorly in English
#' @examples  emotion('很开心', app_id = '1107152791', app_key =  'OpsMj8HXPmbu9SMd')
#' @export
emotion <- function(text, app_key, app_id){
  timestamp_num <- function() {ceiling(as.numeric(as.POSIXct(Sys.time(), format="%Y-%m-%d %H:%M:%S")))}
  nonce_run <- function() {paste0(sample(c(letters, ceiling(runif(10, 0, 9))), 10), collapse = '')}
  params <- c(
    'app_id' = app_id,
    'nonce_str' = nonce_run(),
    'sign' = '',
    'text' = URLencode(enc2utf8(text)),
    'time_stamp' = timestamp_num()
  )
  params['sign'] = get_sign(params, app_key)
  url = 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_textpolar'
  webpage <- RCurl::postForm(url, .params = params)
  result <- jsonlite::fromJSON(webpage)
  return(result$data$polar)
}
suntiansheng/tencentAI documentation built on May 17, 2019, 12:52 p.m.