【问题标题】:How to match strings to large dictionary and avoid memory problems如何将字符串匹配到大字典并避免内存问题
【发布时间】:2020-07-09 11:19:10
【问题描述】:

我有一个包含诸如此类的字符串的数据框,其中一些是现有的英文单词,而另一些则不是:

df <- data.frame(
  strings = c("'tis"," &%#@","aah", "notexistingword", "823942", "abaxile"))

现在我想通过将它们与GradyAugmented 等大型字典进行匹配来检查其中哪些是真实单词;

library(qdapDictionaries)
df$inGrady <- grepl(paste0("\\b(", paste(GradyAugmented[1:2500], collapse = "|"), ")\\b"), df$strings)
df
          strings inGrady
1            'tis    TRUE
2            &%#@   FALSE
3             aah    TRUE
4 notexistingword   FALSE
5          823942   FALSE
6         abaxile    TRUE

不幸的是,只要我限制GradyAugmented 的大小,它就可以正常工作(它似乎不再起作用的截止点大约是2500 的大小)。当我使用 whole 字典时,我得到一个错误,断言有一个 invalid regular expression。我的预感是它不是正则表达式而是内存问题。如何解决这个问题?

【问题讨论】:

  • TRE 和 PCRE 都不支持太长的模式。不确定 ICU 是否会,您可以咨询stringr::str_detect
  • 我认为与其有一个长模式参数 > 2500.. 它可能会更快,如果你这样做应该可以工作pat &lt;- paste0("\\b(", GradyAugmented[1:2500], ")\\b"); Reduce("|", lapply(pat, grepl, x = df$strings))

标签: r regex dictionary memory


【解决方案1】:

你在寻找这样的东西吗?

df$inGrady <- df$strings %in% GradyAugmented

#           strings inGrady
# 1            'tis    TRUE
# 2            &%#@   FALSE
# 3             aah    TRUE
# 4 notexistingword   FALSE
# 5          823942   FALSE
# 6         abaxile    TRUE

【讨论】:

  • 嗯,这是一个很好的解决方案,但我真正想要的是回答我的问题,为什么 grepl 方法会遇到(显然是内存)问题以及如何解决这些问题。
  • 实际上,使用单词边界使建议的方法无效,因为只有当字符串是整个单词时才能找到字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-25
  • 1970-01-01
  • 2015-04-22
  • 2019-05-30
  • 2021-11-27
相关资源
最近更新 更多