2016-10-23 3 views
0

私は以下のサンプルテキストを持っており、機械学習のみを抽出します。Rでは、フォーメーションに関係なく、テキストから特定の単語をマッチして抽出する方法は?

text <- c("Machine Learning is my fav topic.", "I love machinelearning.") 

ifelse((found <- regexpr("\\sMachine Learning", text, 
        perl =TRUE)) !=-1, substring(text, found, 
          found+attr(found,"match.length")), "nothing found") 

しかし、それは私を返します。..

"nothing found" "nothing found" 

私はその結果を取得する必要があります(?i)は、正規表現の場合は鈍感

"Machine Learning", "machinelearning" 

答えて

1

1)あなたは、両方の語句を検索したい場合は:私は2ポイントを持って、下記を参照してください「学習」

library(stringr) 
unlist(str_extract_all(text, "(?i)Machine\\s*Learning")) 
#[1] "Machine Learning" "machinelearning" 
1

に続くゼロ個以上の空白が続くパターン「マシン」(\\s*)を使用します言いますが、 "machine \ s?learning"という表現を使うべきです。 ? \ sの後にスペースは無視されます。

2)regexprを使用して一致を見つけ、regmatches()関数を使用してテキストを抽出します。

> text <- c("Machine Learning is my fav topic.", "I love machinelearning.") 
> m <- regexpr("machine\\s?learning", text, perl=TRUE, ignore.case = TRUE) 
> regmatches (text, m) 

[1] "Machine Learning" "machinelearning" 
関連する問題