【问题标题】:Combination of two words from a sentence一个句子中两个单词的组合
【发布时间】:2017-07-10 08:36:23
【问题描述】:

例如,我需要从 R 中的句子中获取两个单词的组合 ABC 是一个字符串,值为“你好朋友你好吗”

所需的O/p是向量的形式,其中每个元素包含两个单词输出,如

V[1] - "hello friend"
V[2]  - "friend how"
V[3]  -  "how are"
V[4]  -  "are you"

我可以使用此代码获取此信息。请建议是否有更好的方法来做到这一点

Z = 1
for (l in 1:(length(ABC) - 1)) {
  E[z] <- paste(ABC[l], ABC[l+1])
  z <- z + 1 
}

【问题讨论】:

  • 你能试试NGramTokenizer 包中的NGramTokenizer 函数吗?即运行命令NGramTokenizer(x, Weka_control(min = 2, max = 2))
  • 谢谢。 NGramTokenizer 工作正常

标签: r string


【解决方案1】:

你可以用sapply写一个函数:

fun <- function(dat,sep) {
    n = unlist(strsplit(dat,split=sep))
    m = length(n)-1
   sapply(1:m,function(x) paste(n[x],n[x+1]))
}

abc <- c("hello friend how are you")

fun(abc," ")

如果您有要拆分的短语列表,可以将lapply 包裹在函数周围:

abc <- c("hello friend how are you","test sentence one","test sentence two")

lapply(abc,function(y) fun(y," "))

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 2021-10-24
    • 2020-11-18
    • 2010-10-19
    • 2012-11-28
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多