简体   繁体   English

如何清理 R 中的 Twitter 数据?

[英]How do I clean twitter data in R?

I extracted tweets from twitter using the twitteR package and saved them into a text file.我使用 twitteR 包从 twitter 中提取推文并将它们保存到文本文件中。

I have carried out the following on the corpus我已经对语料库进行了以下操作

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')

(using mc.cores=1 and lazy=True as otherwise R on mac is running into errors) (使用 mc.cores=1 和 lazy=True 否则 mac 上的 R 会遇到错误)

tdm<-TermDocumentMatrix(xx)

But this term document matrix has a lot of strange symbols, meaningless words and the like.但是这个词条文档矩阵有很多奇怪的符号,无意义的词等等。 If a tweet is如果一条推文是

 RT @Foxtel: One man stands between us and annihilation: @IanZiering.
 Sharknado‚Äã 3: OH HELL NO! - July 23 on Foxtel @SyfyAU

After cleaning the tweet I want only proper complete english words to be left , ie a sentence/phrase void of everything else (user names, shortened words, urls)清理推文后,我只想留下正确的完整英语单词,即一个没有其他所有内容的句子/短语(用户名、缩写词、网址)

example:例子:

One man stands between us and annihilation oh hell no on 

(Note: The transformation commands in the tm package are only able to remove stop words, punctuation whitespaces and also conversion to lowercase) (注意:tm 包中的转换命令只能去除停用词、标点空格和小写转换)

Using gsub and使用 gsub 和

stringr package字符串包

I have figured out part of the solution for removing retweets, references to screen names, hashtags, spaces, numbers, punctuations, urls .我已经找到了删除转发、对屏幕名称、主题标签、空格、数字、标点符号、网址的引用的部分解决方案。

  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) 

ref: ( Hicks , 2014) After the above I did the below.参考:(希克斯,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]*","")   

ref: (Stanton 2013)参考:(斯坦顿 2013)

Before doing any of the above I collapsed the whole string into a single long character using the below.在执行上述任何操作之前,我使用以下命令将整个字符串折叠成一个长字符。

paste(mytweets, collapse=" ")

This cleaning process has worked for me quite well as opposed to the tm_map transforms.与 tm_map 转换相比,这个清理过程对我来说非常有效。

All that I am left with now is a set of proper words and a very few improper words.我现在只剩下一套合适的词和一些不合适的词。 Now, I only have to figure out how to remove the non proper english words.现在,我只需要弄清楚如何删除不正确的英语单词。 Probably i will have to subtract my set of words from a dictionary of words.可能我将不得不从单词词典中减去我的一组单词。


        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

To remove the URLs you could try the following:要删除 URL,您可以尝试以下操作:

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

Possibly you could define similar functions to further transform the text.也许您可以定义类似的函数来进一步转换文本。

For me, this code did not work, for some reason-对我来说,由于某种原因,这段代码不起作用-

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

Error was-错误是——

Error in stri_replace_all_regex(string, pattern, fix_replacement(replacement),  : 
 Syntax error in regexp pattern. (U_REGEX_RULE_SYNTAX)

So, instead, I used所以,相反,我用

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]*","")

to get rid of URLs摆脱网址

The code do some basic cleaning代码做一些基本的清理

Converts into lowercase转换成小写

df <- tm_map(df, tolower)  

Removing Special characters删除特殊字符

df <- tm_map(df, removePunctuation)

Removing Special characters删除特殊字符

df <- tm_map(df, removeNumbers)

Removing common words删除常用词

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

Removing URL删除网址

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM