2017-04-11 5 views
0

こんにちは私はtidy_text形式で作業しています。文字列 "emails"と "emailing"を "email"に置き換えようとしています。整頓されたテキストフォーマット内のWord置換

set.seed(123) 
terms <- c("emails are nice", "emailing is fun", "computer freaks", "broken modem") 
df <- data.frame(sentence = sample(terms, 100, replace = TRUE)) 
df 
str(df) 
df$sentence <- as.character(df$sentence) 
tidy_df <- df %>% 
unnest_tokens(word, sentence) 

tidy_df %>% 
count(word, sort = TRUE) %>% 
filter(n > 20) %>% 
mutate(word = reorder(word, n)) %>% 
ggplot(aes(word, n)) + 
geom_col() + 
xlab(NULL) + 
coord_flip() 

これは正常に動作しますが、私は使用している場合:

tidy_df <- gsub("emailing", "email", tidy_df) 

言葉に置き換えて、再び棒グラフを実行するために、私は次のエラーメッセージが出ます:UseMethodで

エラー(「group_by_を」 ): 'group_by_'の適用可能なメソッドは、「文字」クラスのオブジェクトに適用されません。

整頓されたテキスト内で簡単に単語を置換する方法を知っている人はいますかtidy_textの構造/クラスを変更することなくフォーマットできますか?

答えて

5

のような言葉の末尾を削除すると、というステミングとなります。あなたが望むなら、それを行うためのRのパッケージがいくつかあります。 1つはhunspell package from rOpenSciであり、別のオプションはPorterアルゴリズムのステミングを実装するSnowballCパッケージです。あなたがそうのようなものを実装します:それはすべてテキストを派生していることを

library(dplyr) 
library(tidytext) 
library(SnowballC) 

terms <- c("emails are nice", "emailing is fun", "computer freaks", "broken modem") 

set.seed(123) 
data_frame(txt = sample(terms, 100, replace = TRUE)) %>% 
     unnest_tokens(word, txt) %>% 
     mutate(word = wordStem(word)) 
#> # A tibble: 253 × 1 
#>  word 
#>  <chr> 
#> 1 email 
#> 2  i 
#> 3  fun 
#> 4 broken 
#> 5 modem 
#> 6 email 
#> 7  i 
#> 8  fun 
#> 9 broken 
#> 10 modem 
#> # ... with 243 more rows 

通告をし、言葉のいくつかは、もはや本当の言葉のように見ていないということ。あなたはそれを気にするかもしれません。

SnowballCやhunspellのようなステマーを使用してすべてのテキストを壊したくない場合は、mutate()にdplyrのif_elseを使用して特定の単語だけを置き換えることができます。

set.seed(123) 
data_frame(txt = sample(terms, 100, replace = TRUE)) %>% 
     unnest_tokens(word, txt) %>% 
     mutate(word = if_else(word %in% c("emailing", "emails"), "email", word)) 
#> # A tibble: 253 × 1 
#>  word 
#>  <chr> 
#> 1 email 
#> 2  is 
#> 3  fun 
#> 4 broken 
#> 5 modem 
#> 6 email 
#> 7  is 
#> 8  fun 
#> 9 broken 
#> 10 modem 
#> # ... with 243 more rows 

それとも、stringrパッケージからstr_replaceを使用することがより多くの意味を作るかもしれません。

library(stringr) 
set.seed(123) 
data_frame(txt = sample(terms, 100, replace = TRUE)) %>% 
     unnest_tokens(word, txt) %>% 
     mutate(word = str_replace(word, "email(s|ing)", "email")) 
#> # A tibble: 253 × 1 
#>  word 
#>  <chr> 
#> 1 email 
#> 2  is 
#> 3  fun 
#> 4 broken 
#> 5 modem 
#> 6 email 
#> 7  is 
#> 8  fun 
#> 9 broken 
#> 10 modem 
#> # ... with 243 more rows 
+0

ニース、stringrパッケージがうまく機能し、私はstr_replaceを使用する場合にのみ、私は1行(代わりに、私は2つのステップでそれをやった)で、いくつかのビットを行うことができませんでした:変異させる(ワード= str_replace(ワード、 "coff(e | eee)"、 "coffee"))。それは "e"と "eee"が同じ文字で始まるからですか? –

関連する問題