【问题标题】:Count number of words in one list that appear in a string计算一个列表中出现在字符串中的单词数
【发布时间】:2015-01-23 12:51:07
【问题描述】:

我在字符向量中有一组独特的单词(已被“提取”),我想知道其中有多少出现在字符串中。

这是我目前所拥有的:

library(RTextTools)

string <- "Players Information donation link controller support years fame glory addition champion Steer leader gang ghosts life Power Pellets tables gobble ghost"
wordstofind <- c("player","fame","field","donat")

# I created a stemmed list of the string
string.stem <- colnames(create_matrix(string, stemWords = T, removeStopwords = F))

我知道下一步可能涉及grepl("\\bword\\b,value") 或一些正则表达式的使用,但我不确定在这种情况下最快的选项是什么。

这是我的标准:

  • 我必须这样做很多次,所以尽可能快是一个问题。
  • 它应该匹配整个单词(“es”不应该匹配“test”)。

任何朝着正确方向的推动都会很棒。

【问题讨论】:

    标签: regex r string grepl


    【解决方案1】:

    嗯,我从不使用庞大的数据集,所以时间从来都不是最重要的,但鉴于您提供的数据,这将让您计算出有多少词完全匹配细绳。可能是一个很好的起点。

    sum(wordstofind %in% unlist(strsplit(string, " ")))
    
    > sum(wordstofind %in% unlist(strsplit(string, " ")))
    [1] 1
    

    编辑感谢@Anthony Bissel:

    sum(wordstofind %in% unlist(string.stem))
    
    > sum(wordstofind %in% unlist(string.stem))
    [1] 3
    

    【讨论】:

    • 结果实际上应该是 3,所以这不起作用,但可能只是您使用了 string 而不是词干向量。
    • 你是怎么得到 3 的?在提供的示例中,唯一的完全匹配和全词匹配是名声。
    • 抱歉,我在解释中并不清楚我将要比较的字符串放在哪里。 sum(wordstofind %in% unlist(string.stem)) 这行得通,看起来你的解决方案比我的要快。请参阅下面的答案。
    • 啊,我想我错过了获取茎的部分。哎呀。好吧,我很高兴它仍然有效。感谢您注意到这一点。
    【解决方案2】:

    看看 Hadley Wickham 的 stringr。您可能正在寻找函数str_count

    【讨论】:

      【解决方案3】:

      当然可能有更快的选择,但这可行:

      length(wordstofind) - length(setdiff(wordstofind, string.stem)) # 3
      

      但看起来 Andrew Taylor 的回答更快:

      `microbenchmark(sum(wordstofind %in% unlist(string.stem)), length(wordstofind) - length(setdiff(wordstofind, string.stem)))
      Unit: microseconds
                                                              expr    min     lq     mean median     uq    max neval
                         sum(wordstofind %in% unlist(string.stem))  4.016  4.909  6.55562  5.355  5.801 37.485   100
      length(wordstofind) - length(setdiff(wordstofind, string.stem)) 16.511 16.958 21.85303 17.404 18.296 81.218   100`
      

      【讨论】:

        猜你喜欢
        • 2014-04-29
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-14
        • 1970-01-01
        • 2021-01-09
        • 1970-01-01
        相关资源
        最近更新 更多