词典列表下载
- 您的第一步是从该链接手动下载(简单的复制和粘贴)词典列表并将其保存为 .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”中的某些术语,这可能不是真的,因此您应该修改您的代码以合并每个术语具有多种影响。