我想使用 R 来比较书面文本并提取元素之间不同的部分。
考虑 a
和 b
两个文本段落。一个是另一个的修改版本:
a <- "This part is the same. This part is old."
b <- "This string is updated. This part is the same."
我想比较两个字符串并接收字符串中对两者中任何一个都是唯一的部分作为输出,最好将两个输入字符串分开。
预期输出:
stringdiff <- list(a = " This part is old.", b = "This string is updated. ")
> stringdiff
$a
[1] " This part is old."
$b
[1] "This string is updated. "
我尝试了来自 Extract characters that differ between two strings 的解决方案,但这只会比较独特的字符。答案在Simple Comparing of two texts in R更接近,但仍然只比较独特的词。
有没有什么方法可以轻松获得预期的输出?
最佳答案
我们连接两个字符串,在 .
后面的空格处分开。创建一个 list
句子 ('lst'),得到 unique
来自 unlist
的元素'lst' ('un1'),使用 setdiff
我们得到不在'un1'中的元素
lst <- strsplit(c(a= a, b = b), "(?<=[.])\\s", perl = TRUE)
un1 <- unique(unlist(lst))
lapply(lst, setdiff, x= un1)
关于r - 使用 R 识别文本段落中的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47548826/