计算两个字符串中相同的单词数

7

I have two strings:

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

我想要计算这些字符串之间的共同单词数量。

答案应该是3。

  • "Roy"

  • "travels"

  • "Africa"

这些都是共同单词。

以下是我的尝试:

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)... - A5C1D2H2I1M1N2O1R2T1
3个回答

10
您可以使用来自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

1
需要将参数“sep”更改为“split” -> a_split <- unlist(strsplit(a, split=" ")) - user131476

8
也许可以使用 intersectstr_extract 来处理多个字符串。你可以将它们作为一个 list 或者 vector
 vec1 <- c(a,b)
 Reduce(`intersect`,str_extract_all(vec1, "\\w+"))
 #[1] "Roy"     "travels" "Africa" 

“对于更快的选项,请考虑使用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

或者使用基本的 R。
  Reduce(`intersect`,regmatches(vec1,gregexpr("\\w+", vec1)))
  #[1] "Roy"     "travels" "Africa" 

2

这种方法可推广到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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接