2017-08-18 15 views
1

データフレーム内の既知のバイグラムを交換する大規模な検索/置換機能/作業コードスニペットを作成できた人はいますか?リストからR tm_map gsubで大規模な置換/トークン化を行う方法は?

例を示します。私はoney-twosie置換えはできませんが、DTM生成の前に単語単位に変換するために、探したい約800語の辞書を活用したいと思っています。たとえば、「Google Analytics」を「google-analytics」に変えたいとします。

私はそれが理論的に可能であることを知っています。基本的に、カスタムストップワードリストは機能的には置き換えなくてもほとんど同じことをします。そして、それはちょうど800gsubsを持っているばかげているようです。

ここに私の現在のコードがあります。任意のヘルプ/ポインタ/ URL/RTFMsは非常に高く評価されるでしょう。

mystopwords <- read.csv(stopwords.file, header = FALSE) 
mystopwords <- as.character(mystopwords$V1) 
mystopwords <- c(mystopwords, stopwords()) 

# load the file 

df <- readLines(file.name) 

# transform to corpus 

doc.vec <- VectorSource(df) 
doc.corpus <- Corpus(doc.vec) 
# summary(doc.corpus) 

## Hit known phrases 

docs <- tm_map(doc.corpus, content_transformer(gsub), pattern = "Google Analytics", replacement = "google-analytics") 

## Clean up and fix text - note, no stemming 

doc.corpus <- tm_map(doc.corpus, content_transformer(tolower)) 
doc.corpus <- tm_map(doc.corpus, removePunctuation,preserve_intra_word_dashes = TRUE) 
doc.corpus <- tm_map(doc.corpus, removeNumbers) 
doc.corpus <- tm_map(doc.corpus, removeWords, c(stopwords("english"),mystopwords)) 
doc.corpus <- tm_map(doc.corpus, stripWhitespace) 

答えて

1

コーパスライブラリを使用すると、単一のトークンに複数の単語からなるフレーズを組み合わせることができます。複数の一致がある場合、それは最長のものを選択します:

library(corpus) 
text_tokens("I live in New York City, New York", 
      combine = c("new york city", "new york")) 

# [[1]] 
# [1] "i"    "live"   "in"   "new_york_city" 
# [5] ","    "new_york" 

デフォルトでは、コネクタは、アンダースコア文字(_)ですが、connector argument`を使用して、代替コネクタを指定することができます。

mycombine <- c("google analytics", "amazon echo") # etc. 
term_matrix(doc.corpus, combine = mycombine, 
      drop_punct = TRUE, drop_number = TRUE, 
      drop = c(stopwords_en, mystopwords)) 

注意また、そのコーパスがイントラワードハイフンを維持し、そうpreserve_intra_word_dashesオプションの必要はありません:あなたの例では

、ドキュメントごとの用語行列を取得するには、以下を行うことができます。

すべての関数呼び出しで前処理オプションを指定するのは面倒です。あなたが希望した場合、あなたはcorpus_frame(特別テキスト列とdata.frame)にごコーパスを変換することができ、その後、前処理オプションを設定する(text_filter):

corpus <- as_corpus_frame(doc.corpus) 
text_filter(corpus) <- text_filter(combine = mycombine, 
            drop_punct = TRUE, 
            drop_number = TRUE, 
            drop = c(stopwords_en, mystopwords)) 

後つまり、あなただけ呼び出すことができますhttp://corpustext.com

コーパス入門ビネットを含めに関するより多くの情報があります

term_matrix(corpus) 

関連する問題