R 中的推特数据清理

twitter data cleaning in R

下面是我的作品。

tweets <- searchTwitter("urban park", n = 2000, lang = "en")
tweets <- strip_retweets(tweets)
text <- sapply(tweets, function(x) x$getText())
text <- gsub("&amp", "", text)
text <- gsub("http\w+", "", text)
text <- gsub("@\w+", "", text)
text <- gsub('[[:punct:]]', '', text)
text <- gsub('[[:cntrl:]]', '', text)
text <- gsub("[[:digit:]]", "", text)
text <- gsub("[ \t]{2,}", "", text)
text <- gsub("^\s+|\s+$", "", text)
mycorpus <- Corpus(VectorSource(text))
inspect(mycorpus[35:50])

结果:......

[22] skateboard skate board scene skate park urban worn street streetlife eauclaire… tcoFvJllsRC

[23] skateboard skate board scene skate park urban worn street streetlife eauclaire… tcoBRbDKOxOs

[24] skateboard skate board scene skate park urban worn street streetlife eauclaire… tcoxlUFDOudRm ......

虽然我在清理文本之前使用功能 strip_retweets 删除了那些转推,但转推仍然如上所示。

还有,如何去掉"tcoFvJllsRC"、"tcoxlUFDOudRm"这样的字眼?它们代表什么?

我的文本清理过程是否正确?

我发现 rtweet 包比 twitteR 更容易使用,后者不再是最新的。

library(rtweet)
tweets <- search_tweets("urban park", n = 2000, lang = "en", full_text = TRUE)

这个returns一个数据框。其中一个列名称是 is_retweet,这使得转发推文的过滤变得容易。或者在 search_tweets().

中使用 include_rts = FALSE
library(dplyr)
tweets <- tweets %>%
  filter(is_retweet == FALSE)

我通常使用 tidytext 包进行文本分析。例如,要将推文文本拆分为单词,过滤掉不需要的单词并删除常见的 "stop words":

tweets <- tweets %>% 
  filter(is_retweet == FALSE) %>%
  select(text) %>%
  unnest_tokens(word, text) %>% 
  select(word) %>% 
  filter(!word %in% c("https", "t.co", "amp"),   # and whatever else to ignore
         !word %in% tolower(tweets$screen_name), # remove user names
         !grepl("^\d+$", word)) %>%             # remove numbers      
  anti_join(stop_words)

你应该接受@neilfws 的回答。这只是添加到其中的一个很好的清洁功能:

clean_tweet_text <- function(x) {

  require(stringi)

  c(
    url_pattern = "http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+",
    handle_pattern = "(^|[^@[:word:]])@([:word:]{1,15})\b",
    entity_pattern = "&[^[:space:]]*;",
    other_pattern = "[[:punct:][:cntrl:][:digit:]]",
    twitter_hashtag_regex <- "(^|[^&\p{L}\p{M}\p{Nd}_\u200c\u200d\ua67e\u05be\u05f3\u05f4\u309b\u309c\u30a0\u30fb\u3003\u0f0b\u0f0c\u00b7])(#|\uFF03)(?!\uFE0F|\u20E3)([\p{L}\p{M}\p{Nd}_\u200c\u200d\ua67e\u05be\u05f3\u05f4\u309b\u309c\u30a0\u30fb\u3003\u0f0b\u0f0c\u00b7]*[\p{L}\p{M}][\p{L}\p{M}\p{Nd}_\u200c\u200d\ua67e\u05be\u05f3\u05f4\u309b\u309c\u30a0\u30fb\u3003\u0f0b\u0f0c\u00b7]*)"
  ) -> pats

  pats <- sprintf("(%s)", paste0(pats, collapse="|"))

  x <- stri_replace_all_regex(x, pats, "")
  x <- stri_trim_both(x)

  x

}