2013-11-01 16 views
8

たとえば、次のような文字列があります。R文字列は分割時に句読点を削除します

x <- 'The world is at end. What do you think? I am going crazy! These people are too calm.' 

私は句読点!?.と、次の空白で分割し、それに句読点を維持する必要があります。

これは句読点を削除し、私は句読点を残す文章を分割することができますどのように

vec <- strsplit(x, '[!?.][:space:]*') 

かかわらず、分割部分の先頭のスペースを残し?

答えて

14

を使用してPCREをオンにして、lookbehindアサーションを使用できます。

strsplit(x, '(?<![^!?.])\\s+', perl=TRUE) 

正規表現:

(?<!   look behind to see if there is not: 
[^!?.]  any character except: '!', '?', '.' 
)    end of look-behind 
\s+   whitespace (\n, \r, \t, \f, and " ") (1 or more times) 

Live Demo

+0

が、それは '[]'グループまたはのためにあるので、 '」.''をエスケープする必要がないことの理由であります何か他の理由? –

+0

PCREや他のいわゆるPerl互換フレーバの場合は、 '。^ $ * +?()[{\ |'文字クラスの外側と '^'、 '-'、'] '、\内部文字クラスをエスケープします。 – hwnd

+0

偉大な、明確化のためにありがとう –

5

sentSplit機能qdap packageでは、ちょうどこのタスクのために作成された:

library(qdap) 
sentSplit(data.frame(text = x), "text") 

## tot      text 
## 1 1.1  The world is at end. 
## 2 2.2   What do you think? 
## 3 3.3   I am going crazy! 
## 4 4.4 These people are too calm. 
2

this questionを見てみましょう。 [:space:]のような文字クラスはブラケット式で定義されているため、角カッコで囲む必要があります。試してください:

vec <- strsplit(x, '[!?.][[:space:]]*') 
vec 
# [[1]] 
# [1] "The world is at end"  "What do you think"   
# [3] "I am going crazy"   "These people are too calm" 

これは先頭の空白を取り除きます。句読点を維持するには、perl = TRUEと正の後読みアサーションを使用します。

vec <- strsplit(x, '(?<=[!?.])[[:space:]]*', perl = TRUE) 
vec 
# [[1]] 
# [1] "The world is at end."  "What do you think?"   
# [3] "I am going crazy!"   "These people are too calm." 
+0

彼は分割後の句読点も欲しかった。 – hwnd

+0

ああ、持っています。私は編集するでしょう - あなたの答えのように見えるでしょう。 '\ [s:]の代わりに' [[:space:]] 'を使ってください。回答の重複は100%ではないので、大丈夫ならば大丈夫です。 –

1

あなたは、文字列、例えばzzzzzと句読点を以下のスペースを交換し、その文字列に分割することができます。置換文字列に\1パターンの括弧で囲まれたサブ表現を指す

x <- gsub("([!?.])[[:space:]]*","\\1zzzzz","The world is at end. What do you think? I am going crazy! These people are too calm.") 
strsplit(x, "zzzzz") 

1

次のようにsent_detect機能を使用することができますqdap version 1.1.0のとおり:

library(qdap) 
sent_detect(x) 

## [1] "The world is at end."  "What do you think?"   
## [3] "I am going crazy!"   "These people are too calm." 
+0

また、2.2.1以降、sent_detect_nlp – demongolem

関連する問題