2017-12-12 1 views
4

私は否定の後に接頭語「not_」を追加する方法について、hereに質問された質問にフォローアップしています。Rの否定、Rの否定に続く単語をどのように置き換えることができますか?

コメントの中で、MrFlickは正規表現gsub("(?<=(?:\\bnot|n't))(\\w+)\\b", "not_\\1", x, perl=T)を使用して解決策を提案しました。

この正規表現を編集して、句読点があるまで "not"または "not"の後に続くすべての単語にnot_という接頭辞を追加します。私はCPTNの例を編集していた場合

、私が欲しい:

x <- "They didn't sell the company, and it went bankrupt" 

がに変換するには:

"They didn't not_sell not_the not_company, and it went bankrupt" 

後方参照の使用はまだここにトリックを行うことができますか?もしそうなら、どんな例でも大歓迎です。ありがとう!

+0

なぜ 'perl'タグカントー? –

+0

@Flying_whale、それらはRが使用を指示できる[tag:pcre]を意味しました。 (上記の 'perl = T' aka' perl = TRUE')。修正されました。 – ikegami

答えて

1

の終わりあなたは使用することができます

(?:\bnot|n't|\G(?!\A))\s+\K(\w+)\b 

と置き換えてnot_\1と置き換えます。 regex demoを参照してください。

詳細

  • (?:\bnot|n't|\G(?!\A)) - 3つの選択肢のいずれか: - 単語全体not
  • n'tからn't
  • \G(?!\A) - 前回の成功のマッチ位置の終わり
    • \bnot
  • \s+ - 1+空白
  • \K - これまで
  • (\w+)に一致したテキストを破棄一致リセットオペレーター - グループ1(置換パターンから\1とを参照):1+単語文字(数字、文字または_
  • \b - 単語の境界。

R demo

x <- "They didn't sell the company, and it went bankrupt" 
gsub("(?:\\bnot|n't|\\G(?!\\A))\\s+\\K(\\w+)\\b", "not_\\1", x, perl=TRUE) 
## => [1] "They didn't not_sell not_the not_company, and it went bankrupt" 
0

最初に、必要な句読点に文字列を分割する必要があります。たとえば:

x <- "They didn't sell the company, and it went bankrupt. Then something else" 
x_split <- strsplit(x, split = "[,.]") 
[[1]] 
[1] "They didn't sell the company" " and it went bankrupt"  " Then something else" 

、その後は、リストx_splitのすべての要素に正規表現を適用します。最後にすべての部分をマージします(必要な場合)。

0

これは理想的ではありませんが、ジョブが行われます:

x <- "They didn't sell the company, and it did not go bankrupt. That's it" 

gsub("((^|[[:punct:]]).*?(not|n't)|[[:punct:]].*?((?<=\\s)[[:punct:]]|$))(*SKIP)(*FAIL)|\\s", 
    " not_", x, 
    perl = TRUE) 

# [1] "They didn't not_sell not_the not_company, and it did not not_go not_bankrupt. That's it" 

注:

これは、あなたが一致するregexでしたくない任意のパターンを避けるために(*SKIP)(*FAIL)トリックを使用しています。文字列または句読点のスタートと"not"または"n't"または

  • 句読点と句読点(スペースが続いていない)

    1. か:これは基本的に、彼らが間に入るものを、スペースを除くnot_ですべてのスペースを置き換えます文字列

  • 関連する問題