Есть ли способ найти указанное c слово на временной шкале Twitter за определенный период времени? - PullRequest
3 голосов
/ 31 января 2020

Я делаю некоторый анализ твиттера в R, сейчас я получаю твиты из учетной записи, но я хочу найти 1 или более указанных c слов в этих твитах, а затем сделать график, который показывает, сколько имеет слово повторялось в течение определенного периода времени, например, 1 недели.

это мой сценарий:

#instalar librerias
library(wordcloud)
library(SnowballC)
library(rtweet)
library(tm)
library(RColorBrewer)
library(tidytext)
library(dplyr)
library(wordcloud2)
library(stringr)
library(qdapRegex)

# Identificacion y obtencion de tokens
appname <- "AnalisisTwitSent"
consumer_key     <- "CvgpjfxMIyUmg21HFPSKoFKr4"
consumer_secret  <- "5VO0fWH6QK5jyYWx4PtABHyhvvZ5JyVjDNjQ2F36mDjYibu5g7"
access_token <- "2820319925-CTKOd9yiA8MmJlak1iXUDCbg2MKkKDlffjr9LyV"
access_secret <- "ZiZBJIjxqY9lNLemYdGxMD6BYM6eY43NyLGhRS4NRKu5S"

twitter_token <- create_token(app = appname, 
                           consumer_key = consumer_key, 
                           consumer_secret = consumer_secret,
                           access_token = access_token, 
                           access_secret = access_secret,
                           set_renv = TRUE)

ver_palabras_comunes_nube <- function(busqueda, cantidad) {

  #Obtener tweets
  #tweets <- get_timeline(usuario, n = cantidad, 
                     #parse = TRUE, check = TRUE,
                     #include_rts = TRUE)
  tweets <- search_tweets(busqueda, cantidad, include_rts = FALSE)

  text <- str_c(tweets$text, collapse = "")

  # continue cleaning the text
  text <- 
    text %>%
    str_remove("\\n") %>%                   # remove linebreaks
    rm_twitter_url() %>%                    # Remove URLS
    rm_url() %>%
    str_remove_all("#\\S+") %>%             # Remove any hashtags
    str_remove_all("@\\S+") %>%             # Remove any @ mentions
    removeWords(stopwords("spanish")) %>%   # Remove common words (a, the, it etc.)
    removeNumbers() %>%
    stripWhitespace() %>%
    removeWords(c("amp"))                   # Final cleanup of other small changes
    gsub("\\p{So}|\\p{Cn}", "", text, perl = TRUE)


  rm_emoticon(text, replacement = "")

  # Convert the data into a summary table
  textCorpus <- 
    Corpus(VectorSource(text)) %>%
    TermDocumentMatrix() %>%
    as.matrix()

  textCorpus <- sort(rowSums(textCorpus), decreasing=TRUE)
  textCorpus <- data.frame(word = names(textCorpus), freq=textCorpus, row.names = NULL)

  wordcloud <- wordcloud2(data = textCorpus, minRotation = 0, maxRotation = 0)
  wordcloud
}

1 Ответ

4 голосов
/ 03 февраля 2020

Чтобы попасть на частотный график с течением времени для определенных c слов, вам нужно только посчитать, как часто они появляются в каждом временном интервале, а затем построить их. Я использую пакет tidytext, который отлично подходит для этого. Но вы также можете подумать о том, чтобы просто использовать stringr::str_count() (хотя в этом случае следите или исправьте токенизацию) Вы помещаете свой код в функцию, которая в данном случае на самом деле не нужна, но я написал код, чтобы вы могли быстро поместить его обратно в функцию, если хотите.

library(rtweet)
library(tidyverse)
library(tidytext)

# define variables
busqueda <- "Poppycock"   
cantidad <- 100
pattern <- c("is", "to")

# query tweets
tweets <- search_tweets(busqueda, cantidad, include_rts = FALSE)


# count the occurence of the pattern words
pattern_df <- tweets %>% 
  select(status_id, text, created_at) %>%          # only keep data columns we need later
  unnest_tokens(word, text) %>%                    # split the text into tokens (words)
  filter(word %in% pattern) %>%                    # only keept words defined in pattern
  mutate(hour = lubridate::hour(created_at)) %>%   # extract the hour from the created_at time, use week here if you want
  count(word, hour)                                # count the words per hour

# plot
ggplot(pattern_df, aes(x = hour, y = n, fill = word)) +
  geom_col(position = "dodge")

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...