有没有办法使用R从字符串中提取没有空格或其他分隔符的单词?我有一个URL列表,我想弄清楚URL中包含哪些单词.
input <- c("babybag", "badshelter", "themoderncornerstore", "hamptonfamilyguidebook")
Run Code Online (Sandbox Code Playgroud)
这是一个天真的方法,可能会给你灵感,我使用库,hunspell但你可以测试任何字典的子串.
我从右边开始,尝试每个子字符串并保持我在字典中找到的最长的字符串,然后改变我的起始位置,这很慢,所以我希望你没有4百万个.hampton不在这本词典中,所以它没有为最后一个给出正确的结果:
split_words <- function(x){
candidate <- x
words <- NULL
j <- nchar(x)
while(j !=0){
word <- NULL
for (i in j:1){
candidate <- substr(x,i,j)
if(!length(hunspell::hunspell_find(candidate)[[1]])) word <- candidate
}
if(is.null(word)) return("")
words <- c(word,words)
j <- j-nchar(word)
}
words
}
input <- c("babybag", "badshelter", "themoderncornerstore", "hamptonfamilyguidebook")
lapply(input,split_words)
# [[1]]
# [1] "baby" "bag"
#
# [[2]]
# [1] "bad" "shelter"
#
# [[3]]
# [1] "the" "modern" "corner" "store"
#
# [[4]]
# [1] "h" "amp" "ton" "family" "guidebook"
#
Run Code Online (Sandbox Code Playgroud)
这是一个快速修复,手动向字典添加单词:
split_words <- function(x, additional = c("hampton","otherwordstoadd")){
candidate <- x
words <- NULL
j <- nchar(x)
while(j !=0){
word <- NULL
for (i in j:1){
candidate <- substr(x,i,j)
if(!length(hunspell::hunspell_find(candidate,ignore = additional)[[1]])) word <- candidate
}
if(is.null(word)) return("")
words <- c(word,words)
j <- j-nchar(word)
}
words
}
input <- c("babybag", "badshelter", "themoderncornerstore", "hamptonfamilyguidebook")
lapply(input,split_words)
# [[1]]
# [1] "baby" "bag"
#
# [[2]]
# [1] "bad" "shelter"
#
# [[3]]
# [1] "the" "modern" "corner" "store"
#
# [[4]]
# [1] "hampton" "family" "guidebook"
#
Run Code Online (Sandbox Code Playgroud)
你可以只是交叉手指,不要有任何模糊的表达.请注意,"guidebook"在我的输出中只有一个单词,所以我们在四个示例中已经有了一个边缘情况.