我正在进行情感分析,并希望所有否定词都以否定词(例如“ did n't”)开头。使用%in%
可以与简单的字符串配合使用,但对于包含特殊字符(例如撇号)的字符串,则不适用于我的文本。
文字中的字母:
> head(sup4_bigrams_count,3)
# A tibble: 3 x 3
word1 word2 n
<chr> <chr> <int>
1 parent’s day 8
2 mother’s day 7
3 bachelor’s degree 6
> sup4_bigrams_count$word1 %>% unique
......
[61] "daily" "day" "de" "define"
[65] "depth" "developed" "didn’t" "differentiated"
[69] "difunctioning" "diploma" "doesn’t" "don’t"
我有兴趣获得以“ did n't”,“ dosn't”和“ do n't”开头的二元组。但是请注意,这些单词是’
而不是'
,所以我直接从文本中复制了这些单词。对于“不”和“不”也类似。可以,但是一次只映射一个单词。
> sup4_bigrams_count %>% filter(str_detect(word1,"didn’t"))
# A tibble: 3 x 3
word1 word2 n
<chr> <chr> <int>
1 didn’t argue 1
2 didn’t miss 1
3 didn’t shame 1
但是使用%in%根本不起作用。
negate_words <- c("didn’t","doesn’t","don’t")
> sup4_bigrams_count %>% filter(word1 %in% negate_words)
# A tibble: 0 x 3
# ... with 3 variables: word1 <chr>, word2 <chr>, n <int>
但是,如果我使用这些词来创建另一个数据框,则%in%可以正常工作。
a <- data_frame(word=c("didn’t","doesn’t","don’t"),ind=1:3)
n <- c("didn’t","doesn’t")
> a %>% filter(word %in% n)
# A tibble: 2 x 2
word ind
<chr> <int>
1 didn’t 1
2 doesn’t 2
我只能做的是str_detect
过滤三次并rbind
一起过滤,但是这很麻烦,而且如果我的否定词列表很长,也不会很容易。希望有人可以帮忙。
答案 0 :(得分:1)
您可以构建一个“或”正则表达式来一次搜索所有否定词。
library(stringr)
negate_words <- c("didn’t","doesn’t","don’t")
strings <- c("daily", "day", "de", "define",
"depth", "developed", "didn’t", "differentiated",
"difunctioning", "diploma", "doesn’t", "don’t")
str_detect(strings, "didn’t")
# FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE
pattern <- paste0("(", paste(negate_words, collapse="|"), ")")
pattern
# "(didn’t|doesn’t|don’t)"
str_detect(strings, pattern)
# FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE TRUE TRUE