词典列表下载
- 您的第一步是从此链接手动下载(简单的复制和粘贴)词典列表并将其保存为 .csv 格式:
http://www.saifmohammad.com/WebDocs/NRC-AffectIntensity-Lexicon.txt
然后你需要把这个列表分解成 4 个独立的部分,每个部分应该有一个影响。这将产生 4 个 .csv 文件:
anger_list = w.csv
fear_list = x.csv
joy_list = y.csv
sad_list = z.csv
如果您不想手动执行此操作,还有一个替代词典列表,其中数据可直接下载到单独的文件中:https ://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html#lexicon
文字资料下载
- 您共享的另一个链接(http://webrobots.io/Kickstarter-datasets/)现在似乎同时具有 JSON 和 csv 文件,并且将其读入 R 似乎非常简单。
清理用于文本提取的 URL
- 我不确定您有兴趣分析的列/字段;因为我在 2019 年 2 月下载的数据集没有“p”字段。
由于您提到了 URL 的存在,我还分享了一个简短的代码,用于可能的 URL 编辑或清理。这将帮助您从 URL 中获取干净的文本数据:
replacePunctuation <- function(x)
{
# Lowercase all words for convenience
x <- tolower(x)
# Remove words with multiple consecutive digits in them (3 in this case)
x <- gsub("[a-zA-Z]*([0-9]{3,})[a-zA-Z0-9]* ?", " ", x)
# Remove extra punctuation
x <- gsub("[.]+[ ]"," ",x) # full stop
x <- gsub("[:]+[ ]"," ",x) # Colon
x <- gsub("[?]"," ",x) # Question Marks
x <- gsub("[!]"," ",x) # Exclamation Marks
x <- gsub("[;]"," ",x) # Semi colon
x <- gsub("[,]"," ",x) # Comma
x <- gsub("[']"," ",x) # Apostrophe
x <- gsub("[-]"," ",x) # Hyphen
x <- gsub("[#]"," ",x)
# Remove all newline characters
x <- gsub("[\r\n]", " ", x)
# Regex pattern for removing stop words
stop_pattern <- paste0("\\b(", paste0(stopwords("en"), collapse="|"), ")\\b")
x <- gsub(stop_pattern, " ", x)
# Replace whitespace longer than 1 space with a single space
x <- gsub(" {2,}", " ", x)
x
}
用于添加情绪或影响分数的代码
接下来,我假设您已将数据作为 R 中的文本读取。假设您已将其存储为某些数据框df$p的一部分。然后下一步是向此数据框添加其他列:
df$p # contains text of interest
现在为四个影响中的每一个添加额外的列到这个数据框
df$ANGER = 0
df$FEAR = 0
df$JOY = 0
df$SADNESS = 0
然后,您只需遍历df的每一行,将文本p分解为基于空格的单词。然后你从你的词典列表中寻找特定术语的出现到你得到的剥离词中。然后,您为每个影响分配分数,如下所示:
for (i in 1:nrow(df))
{
# counter initialization
angry = 0
feared = 0
joyful = 0
sad = 0
# for df, let's say the text 'p' is at first column place
words <- strsplit(df[i,1], " ")[[1]]
for (j in 1:length(words))
{
if (words[j] %in% anger_list[,1])
angry = angry + 1
else {
if (words[j] %in% fear_list[,1])
feared = feared + 1
else {
if (words[j] %in% joy_list[,1])
joyful = joyful + 1
else
sad = sad + 1
} #else 2
} #else 1
} #for 2
df[i,2] <- angry
df[i,3] <- feared
df[i,4] <- joyful
df[i,5] <- sad
}#for 1
请注意,在上述实现中,我假设一个词一次只能代表一种影响。这意味着我假设这些影响是相互排斥的。但是,我知道对于您的文本“p”中的某些术语,这可能不是真的,因此您应该修改代码以合并每个术语具有多种影响。