从R中的句子中提取单词

时间:2016-11-08 19:35:22

标签: r string text

我正在尝试提取后面跟着某些字母的单词。例如,在这个例子中,我试图提取' AB'

之后的单词
x = c("So much fun - AB22148",                       
"AC33648 does whatever",                           
"I know -AB11025 Failed",                   
"Nothing stalled - AB16228",        
"Unable to do fdS2083D - Ab26604")

Num = character(0)
for (i in 1:length(x)) {
   y = unlist(strsplit(x[i]," "))
   Num[i] = grep("AB",y, perl = T, value = T, ignore.case = T)
  }

有几个问题(你可能会说):1。如果' AB'不存在然后我得到一个错误,因为Num不能采取零长度。 2.如果我克服了这个问题(例如,通过用AB替换AC),那么第5个条目就让我无法做到这一点。而不是" Ab26604"。

我正在寻找的是:1。可以在没有循环的情况下完成(可能使用其中一个应用功能)2。如何考虑第3和第5种情况? [我想删除' - '标志(我可以在下一步处理这个问题,但想知道它是否可以同时完成)]

   Num (current output)
  [1] "AB22148"  " "  "-AB11025" "AB16228"  "Unable" 

  Num (required output)
 [1] "AB22148"  " "  "AB11025" "AB16228"  "Ab26604" 

感谢所有帮助。对此,我真的非常感激。如果您需要进一步澄清,请告诉我

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

require(stringr)
str_extract(x, regex("AB[:alnum:]{5}", ignore_case = TRUE))

这给了你:

"AB22148" NA        "AB11025" "AB16228" "Ab26604"

如果您想要NA替换" ",您可以这样做:

str_replace_na(tmp, " ") # assuming tmp is the result from above

这给了你:

"AB22148" " "       "AB11025" "AB16228" "Ab26604"