【问题标题】:R: detect words and punctuation marks in textR:检测文本中的单词和标点符号
【发布时间】:2015-03-20 11:58:11
【问题描述】:

我有一些自然出现的文字:

   text="word1 word2 word3. word4, word5 word6 word7"

以及我想在该文本中检测到的一些元素:

elements=c("word2","word6 word7",".",",")

然而,

 elements[sapply(paste0("\\<",elements,"\\>"),grepl,text)]

只返回一元“word2”和二元“word6 word7”。未检测到文本中的句点和逗号。

我怎样才能做到这一点?

【问题讨论】:

    标签: regex r text detection grepl


    【解决方案1】:

    您不需要包含方括号,因为方括号是正则表达式中的特殊元字符,表示字符类。

    > text="word1 word2 word3. word4, word5 word6 word7"
    > elements=c("word2","word6 word7",".",",")
    > elements[sapply(paste0(elements),grepl,text, fixed=T)]
    [1] "word2"       "word6 word7" "."           ","  
    

    【讨论】:

    • 谢谢!那么,在哪些情况下你使用 \\\\ 和 [ ] ?
    • 不是来自我的
    • \\&lt; 匹配单词 char 和非单词 char,\\&gt; 匹配非单词 char 和单词 char。所以在3. 中退出的. 不会满足这一点,因为在点之后没有单词char 退出。逗号也一样。
    【解决方案2】:
    elements[sapply(paste0("[",elements,"]"),grepl,text)] does the job. 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      相关资源
      最近更新 更多