如何在R中清洗Twitter数据?

14

我使用twitteR软件包从Twitter中提取了推文,并将它们保存到文本文件中。

我对语料库进行了以下处理

xx<-tm_map(xx,removeNumbers, lazy=TRUE, 'mc.cores=1')
xx<-tm_map(xx,stripWhitespace, lazy=TRUE, 'mc.cores=1')
xx<-tm_map(xx,removePunctuation, lazy=TRUE, 'mc.cores=1')
xx<-tm_map(xx,strip_retweets, lazy=TRUE, 'mc.cores=1')
xx<-tm_map(xx,removeWords,stopwords(english), lazy=TRUE, 'mc.cores=1')

(使用mc.cores = 1和lazy = True,否则在Mac上使用R时会遇到错误)

tdm<-TermDocumentMatrix(xx)

但是这个术语文档矩阵中有很多奇怪的符号、无意义的词语等等。 如果一个推文是

 RT @Foxtel: One man stands between us and annihilation: @IanZiering.
 Sharknado‚Äã 3: OH HELL NO! - July 23 on Foxtel @SyfyAU
在清理推文后,我希望只保留适当完整的英文单词,即句子/短语中不包含其他任何内容(用户名,缩写词,URL)。
例如:
One man stands between us and annihilation oh hell no on 

(注意:tm包中的转换命令仅能删除停用词、标点符号、空格并转换为小写)


然后,sharknadofoxtel就完成了,因为它们不是“正确”的英语单词... - Marc B
如果您使用 xx <- tm_map(xx, content_transformer(removePunctuation) 或者 xx <- tm_map(xx, content_transformer(tolower)),您是否看到了任何改进? - RHertel
精确的语法可能取决于您安装的 tm 包的版本号。 - RHertel
5个回答

18

使用gsub和stringr包

我已经找到了删除转推,提及屏幕名称,主题标签,空格,数字,标点符号,网址的部分解决方案。

  clean_tweet = gsub("&amp", "", unclean_tweet)
  clean_tweet = gsub("(RT|via)((?:\\b\\W*@\\w+)+)", "", clean_tweet)
  clean_tweet = gsub("@\\w+", "", clean_tweet)
  clean_tweet = gsub("[[:punct:]]", "", clean_tweet)
  clean_tweet = gsub("[[:digit:]]", "", clean_tweet)
  clean_tweet = gsub("http\\w+", "", clean_tweet)
  clean_tweet = gsub("[ \t]{2,}", "", clean_tweet)
  clean_tweet = gsub("^\\s+|\\s+$", "", clean_tweet) 

参考文献: (Hicks, 2014) 在上述操作之后, 我进行了以下操作。

 #get rid of unnecessary spaces
clean_tweet <- str_replace_all(clean_tweet," "," ")
# Get rid of URLs
clean_tweet <- str_replace_all(clean_tweet, "http://t.co/[a-z,A-Z,0-9]*{8}","")
# Take out retweet header, there is only one
clean_tweet <- str_replace(clean_tweet,"RT @[a-z,A-Z]*: ","")
# Get rid of hashtags
clean_tweet <- str_replace_all(clean_tweet,"#[a-z,A-Z]*","")
# Get rid of references to other screennames
clean_tweet <- str_replace_all(clean_tweet,"@[a-z,A-Z]*","")   

参考文献:(Stanton 2013)

在进行任何上述操作之前,我使用以下方法将整个字符串折叠成一个长字符。

paste(mytweets, collapse=" ")

这个清理过程对我来说非常有效,而不是使用tm_map转换。

现在,我只剩下一组正确的单词和非常少量的不正确的单词。 现在,我只需要找出如何去除非正确的英语单词。 可能我需要从字典中减去我的单词集合。


1
这个很好用,但是请确保你不要在参数中使用 clean_tweet,除非你想覆盖变量! - timothyjgraham
1
请确保顺序正确。如果您首先删除提及,然后进行RT检查(clean_tweet <- str_replace(clean_tweet,"RT @[a-z,A-Z]*: ","")),它将找不到任何内容,因为@已经不存在了。 - Mathias711

8

        library(tidyverse)    
        
        clean_tweets <- function(x) {
                    x %>%
                            # Remove URLs
                            str_remove_all(" ?(f|ht)(tp)(s?)(://)(.*)[.|/](.*)") %>%
                            # Remove mentions e.g. "@my_account"
                            str_remove_all("@[[:alnum:]_]{4,}") %>%
                            # Remove hashtags
                            str_remove_all("#[[:alnum:]_]+") %>%
                            # Replace "&" character reference with "and"
                            str_replace_all("&amp;", "and") %>%
                            # Remove puntucation, using a standard character class
                            str_remove_all("[[:punct:]]") %>%
                            # Remove "RT: " from beginning of retweets
                            str_remove_all("^RT:? ") %>%
                            # Replace any newline characters with a space
                            str_replace_all("\\\n", " ") %>%
                            # Make everything lowercase
                            str_to_lower() %>%
                            # Remove any trailing whitespace around the text
                            str_trim("both")
            }
    
        tweets %>% clean_tweets

1
能否在每个步骤中得到被移除的内容的注释?我正在学习正则表达式,但仍然有问题识别某些表达式。谢谢。 - k3r0
2
@k3r0 - 我已经为每个步骤添加了注释,以更清晰地说明它正在做什么。 - RDRR
1
我对此进行了一些阅读,并弄清楚了其中的一些内容,但并非全部。我并不熟悉执行函数,所以这是一个很好的学习机会。谢谢! - k3r0

2

要删除URL,您可以尝试以下操作:

removeURL <- function(x) gsub("http[[:alnum:]]*", "", x)
xx <- tm_map(xx, removeURL)

也许你可以定义类似的函数来进一步转换文本。

1

对我来说,这段代码不起作用,原因不明-

# Get rid of URLs
clean_tweet <- str_replace_all(clean_tweet, "http://t.co/[a-z,A-Z,0-9]*{8}","")

错误信息为-
Error in stri_replace_all_regex(string, pattern, fix_replacement(replacement),  : 
 Syntax error in regexp pattern. (U_REGEX_RULE_SYNTAX)

因此,我使用了


clean_tweet4 <- str_replace_all(clean_tweet3, "https://t.co/[a-z,A-Z,0-9]*","")
clean_tweet5 <- str_replace_all(clean_tweet4, "http://t.co/[a-z,A-Z,0-9]*","")

去掉URL链接


0

该代码执行了一些基本的清理操作

转换为小写字母

df <- tm_map(df, tolower)  

移除特殊字符

df <- tm_map(df, removePunctuation)

去除特殊字符

df <- tm_map(df, removeNumbers)

去除常见词

df <- tm_map(df, removeWords, stopwords('english'))

移除URL

removeURL <- function(x) gsub('http[[:alnum;]]*', '', x)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接