【问题标题】:twitter data cleaning in RR中的twitter数据清理
【发布时间】:2017-11-22 12:41:53
【问题描述】:

下面是我的作品。

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”等字词?它们代表什么?

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

【问题讨论】:

标签: r data-cleaning


【解决方案1】:

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

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

这会返回一个数据框。其中一个列名是is_retweet,这使得过滤转发变得容易。或者只是在search_tweets() 中使用include_rts = FALSE

library(dplyr)
tweets <- tweets %>%
  filter(is_retweet == FALSE)

我通常使用tidytext 包进行文本分析。例如,要将推文文本拆分为单词,过滤掉您不想要的单词并删除常见的“停用词”:

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)

【讨论】:

  • 那么我应该使用 tm_map 来完成词干补全吗?或者还有另一组代码来完成词干补全。 (我想清理推特数据生成wordcloud,分析词之间的关系,进行情感分析,所以我需要先做词干补全过程)
【解决方案2】:

您应该接受@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

}

【讨论】:

    猜你喜欢
    • 2015-09-29
    • 1970-01-01
    • 2015-11-10
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 2020-09-02
    相关资源
    最近更新 更多