【问题标题】:Count common words in two strings计算两个字符串中的常用词
【发布时间】:2014-11-13 20:23:33
【问题描述】:

我有两个字符串:

a <- "Roy lives in Japan and travels to Africa"
b <- "Roy travels Africa with this wife"

我希望计算这些字符串之间的常用词。

答案应该是 3。

  • “罗伊”

  • “旅行”

  • “非洲”

常用词

这是我尝试过的:

stra <- as.data.frame(t(read.table(textConnection(a), sep = " ")))
strb <- as.data.frame(t(read.table(textConnection(b), sep = " ")))

取唯一以避免重复计数

stra_unique <-as.data.frame(unique(stra$V1))
strb_unique <- as.data.frame(unique(strb$V1))
colnames(stra_unique) <- c("V1")
colnames(strb_unique) <- c("V1")

common_words <-length(merge(stra_unique,strb_unique, by = "V1")$V1)

对于包含超过 2000 和 1200 个字符串的数据集,我需要这样做。 我必须评估字符串的总时间是 2000 X 1200。任何快速的方法,不使用循环。

【问题讨论】:

  • 我并不是真的推荐这个,但是使用你的“stra”和“strb”,你可能就可以做到merge(stra, strb)...

标签: r string text-mining data-analysis


【解决方案1】:

这种方法可推广到 n 个向量:

a <- "Roy lives in Japan and travels to Africa"
b <- "Roy travels Africa with this wife"
c <- "Bob also travels Africa for trips but lives in the US unlike Roy."

library(stringi);library(qdapTools)
X <- stri_extract_all_words(list(a, b, c))
X <- mtabulate(X) > 0
Y <- colSums(X) == nrow(X); names(Y)[Y]

[1] "Africa"  "Roy"     "travels"

【讨论】:

    【解决方案2】:

    也许,使用intersectstr_extract 对于multiple strings,您可以将它们设置为listvector

     vec1 <- c(a,b)
     Reduce(`intersect`,str_extract_all(vec1, "\\w+"))
     #[1] "Roy"     "travels" "Africa" 
    

    对于faster 选项,请考虑stringi

     library(stringi)
     Reduce(`intersect`,stri_extract_all_regex(vec1,"\\w+"))
     #[1] "Roy"     "travels" "Africa" 
    

    计数:

     length(Reduce(`intersect`,stri_extract_all_regex(vec1,"\\w+")))
     #[1] 3
    

    或使用base R

      Reduce(`intersect`,regmatches(vec1,gregexpr("\\w+", vec1)))
      #[1] "Roy"     "travels" "Africa" 
    

    【讨论】:

      【解决方案3】:

      您可以使用base 库中的strsplitintersect

      > a <- "Roy lives in Japan and travels to Africa"
      > b <- "Roy travels Africa with this wife"
      > a_split <- unlist(strsplit(a, sep=" "))
      > b_split <- unlist(strsplit(b, sep=" "))
      > length(intersect(a_split, b_split))
      [1] 3
      

      【讨论】:

      • 参数“sep”需要改为“split” -> a_split
      猜你喜欢
      • 1970-01-01
      • 2021-02-15
      • 2013-10-16
      • 1970-01-01
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多