gpt4 book ai didi

r - 我如何 'efficiently' 在大型文本语料库中用另一个(成对)替换字符串向量

转载 作者:行者123 更新时间:2023-12-04 13:01:38 26 4
gpt4 key购买 nike

我在字符串向量中有大量文本(大约 700.000 个字符串)。我正在尝试替换语料库中的特定单词/短语。也就是说,我有一个包含 app 40.000 个短语的向量和一个相应的替换向量。

我正在寻找解决问题的有效方法

我可以在 for 循环中完成,循环遍历每个模式 + 替换。但它的扩展性很差(3 天左右!)

我也试过 qdap::mgsub(),但它似乎也很糟糕

txt <- c("this is a random sentence containing bca sk", 
"another senctence with bc a but also with zqx tt",
"this sentence contains non of the patterns",
"this sentence contains only bc a")

patterns <- c("abc sk", "bc a", "zqx tt")

replacements <- c("@a-specfic-tag-@abc sk",
"@a-specfic-tag-@bc a",
"@a-specfic-tag-@zqx tt")

#either
txt2 <- qdap::mgsub(patterns, replacements, txt)
#or
for(i in 1:length(patterns)){
txt <- gsub(patterns[i], replacements[i], txt)
}


这两种解决方案对于我的应用程序 40.000 模式/替换和 700.000 txt 字符串的数据的扩展都很糟糕

我认为必须有一种更有效的方法来做到这一点?

最佳答案

如果您可以先标记文本,那么矢量化替换会快得多。如果 a) 您可以使用多线程解决方案并且 b) 您使用固定而不是正则表达式匹配,它也会更快。

以下是在 中执行所有操作的方法量子达包裹。最后一行将标记作为字符向量粘贴回单个“文档”中,如果这是您想要的。

library("quanteda")
## Package version: 1.4.3
## Parallel computing: 2 of 12 threads used.
## See https://quanteda.io for tutorials and examples.
##
## Attaching package: 'quanteda'
## The following object is masked from 'package:utils':
##
## View
quanteda_options(threads = 4)

txt <- c(
"this is a random sentence containing bca sk",
"another sentence with bc a but also with zqx tt",
"this sentence contains none of the patterns",
"this sentence contains only bc a"
)
patterns <- c("abc sk", "bc a", "zqx tt")
replacements <- c(
"@a-specfic-tag-@abc sk",
"@a-specfic-tag-@bc a",
"@a-specfic-tag-@zqx tt"
)

这将标记文本,然后使用固定模式匹配快速替换散列类型(但您可以使用 valuetype = "regex" 进行正则表达式匹配)。通过包装 patternsphrases()功能,你说的是 tokens_replace()查找标记序列而不是单个匹配项,因此这解决了多字问题。

toks <- tokens(txt) %>%
tokens_replace(phrase(patterns), replacements, valuetype = "fixed")
toks
## tokens from 4 documents.
## text1 :
## [1] "this" "is" "a" "random" "sentence"
## [6] "containing" "bca" "sk"
##
## text2 :
## [1] "another" "sentence"
## [3] "with" "@a-specfic-tag-@bc a"
## [5] "but" "also"
## [7] "with" "@a-specfic-tag-@zqx tt"
##
## text3 :
## [1] "this" "sentence" "contains" "none" "of" "the"
## [7] "patterns"
##
## text4 :
## [1] "this" "sentence" "contains"
## [4] "only" "@a-specfic-tag-@bc a"

最后,如果您真的想将其重新转换为字符格式,请转换为字符类型列表,然后将它们粘贴在一起。

sapply(as.list(toks), paste, collapse = " ")
## text1
## "this is a random sentence containing bca sk"
## text2
## "another sentence with @a-specfic-tag-@bc a but also with @a-specfic-tag-@zqx tt"
## text3
## "this sentence contains none of the patterns"
## text4
## "this sentence contains only @a-specfic-tag-@bc a"

您必须在大型语料库上对此进行测试,但 70 万个字符串听起来并不是一项太大的任务。请试试这个并报告它是如何做到的!

关于r - 我如何 'efficiently' 在大型文本语料库中用另一个(成对)替换字符串向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55435345/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com