2017-11-17 7 views
2

から単語を削除します。私は、データフレームから特定の単語を削除しようとしている文字列

name age words 
James 34 hello, my name is James. 
John 30 hello, my name is John. Here is my favourite website https://stackoverflow.com 
Jim 27 Hi! I'm another persoon whose name begins with a J! Here is something that should be filtered out: <filter> 

df<-structure(list(name = structure(c(1L, 3L, 2L), .Label = c("James", 
"Jim", "John"), class = "factor"), age = c(34L, 30L, 27L), message = structure(1:3, .Label = c("hello, my name is James. ", 
"hello, my name is John. Here is my favourite website https://stackoverflow.com", 
"Hi! I'm another persoon whose name begins with a J! Here is something that should be filtered out: <filter>" 
), class = "factor")), .Names = c("name", "age", "message"), class = "data.frame", row.names = c(NA, 
-3L)) 

私はhttpまたはfilterにマッチを含むすべての単語を削除しようとしています。

各行を繰り返し、空白文字列を分割して、単語にhttpまたは<filter>(または他の単語)が含まれているかどうかを尋ねます。もしそうなら、その単語をスペースで置き換えたいと思います。

がexatly別の単語、または単語のリストと一致するが、私はいくつかの基準(例えばhttpまたはwww.)と一致する単語を削除するには多くを見つけることができない単語を削除に関するloadofquestionsがあります。

gsub!grepltm_mapアプローチ(例えばthis)を、私は私の期待される出力を生成するためにそれらのいずれかを取得することはできません:

私が試した

name age words 
James 34 hello, my name is James. 
John 30 hello, my name is John. Here is my favourite website 
Jim 27 Hi! I'm another persoon whose name begins with a J! Here is something that should be filtered out: 
+0

あなたの最後の行に "フィルタ" 単語が 'filter'と一致し、あなたの説明に基づいて、削除する必要があります。あなたが ''を意味しない限り。 – AntoniosK

+1

@AntoniosK - あなたが正しいです。私は質問 – fugu

+0

を更新しました。以下の答えは間違いなくあなたを助けます.... – AntoniosK

答えて

2

続き任意の非空白チャンクを削除するには

(?:\s+|^)\S*(?<!\w)(?:https?|<filter>)(?!\w)\S* 

regex demo

詳細を参照してください:あなたは、次のPCRE正規表現(perl=TRUE引数を追加します)とgsubを使用することができ単語全体としてhttpまたはfilter(つまり)のいずれかをaining

  • (?:\s+|^) - 1+ wjhitespacesまたは文字列の先頭
  • \S* - 0+非空白文字できるだけ多く
  • (?<!\w) - 現在位置のすぐ左に不可ワードチャー
  • (?:https?|<filter>)からhttphttps又は<filter>
  • (?!\w) - 現在位置のすぐ右に不可ワードチャー
  • \S*(交互グループ内の単語の後) - できるだけ多く0+非空白文字。

online R demoを参照してください:

df<-structure(list(name = structure(c(1L, 3L, 2L), .Label = c("James", 
"Jim", "John"), class = "factor"), age = c(34L, 30L, 27L), message = structure(1:3, .Label = c("hello, my name is James. ", 
"hello, my name is John. Here is my favourite website https://stackoverflow.com", 
"Hi! I'm another persoon whose name begins with a J! Here is something that should be filtered out: <filter>" 
), class = "factor")), .Names = c("name", "age", "message"), class = "data.frame", row.names = c(NA, 
-3L)) 
df$message <- gsub("(?:\\s+|^)\\S*(?<!\\w)(?:https?|<filter>)(?!\\w)\\S*", "", df$message, perl=TRUE) 
df$message 

結果:

[1] "hello, my name is James. "                   
[2] "hello, my name is John. Here is my favourite website"            
[3] "Hi! I'm another persoon whose name begins with a J! Here is something that should be filtered out:" 
2
我々が使用することができます

gsub

gsub("\\s(https:\\S+|<filter>)", "", df$message) 
関連する問題