2016-04-19 3 views
1

特定のWebページに基づいて少なくとも2回出現する単語のリストを作成したいと思います。 データを取得し、各単語ごとにカウントを持つリストを取得することに成功しましたが、 この方法をとどめるために大文字の単語を保持する必要があります。今度は、小文字だけの単語リストが生成されます。 たとえば、「マイアミ」という言葉は「マイアミ」に変わり、「マイアミ」として必要になります。テキストマイニング中に単語の元の構造を保持する方法

どのようにして元の構造で単語を取得できますか?

コードが取り付けられている。

library(XML) 
web_page <- htmlTreeParse("http://www.larryslist.com/artmarket/the-talks/dennis-scholls-multiple-roles-from-collecting-art-to-winning-emmy-awards/" 
          ,useInternal = TRUE) 

doctext = unlist(xpathApply(web_page, '//p', xmlValue)) 
doctext = gsub('\\n', ' ', doctext) 
doctext = paste(doctext, collapse = ' ') 

library(tm) 
SampCrps<- Corpus(VectorSource(doctext)) 
corp <- tm_map(SampCrps, PlainTextDocument) 

oz <- tm_map(corp, removePunctuation, preserve_intra_word_dashes = FALSE) # remove punctuation 
oz <- tm_map(corp, removeWords, stopwords("english")) # remove stopwords 
dtm <-DocumentTermMatrix(oz) 

findFreqTerms(dtm,2) # words that apear at least 2 times 
dtmMatrix <- as.matrix(dtm) 
wordsFreq <- colSums(dtmMatrix) 
wordsFreq <- sort(wordsFreq, decreasing=TRUE) 
head(wordsFreq) 
wordsFreq <- as.data.frame(wordsFreq) 
wordsFreq <- data.frame(word = rownames(wordsFreq), count = wordsFreq, row.names = NULL) 
head(wordsFreq,50) 

私は3つのワードnグラムを取得するには、コードのこの行を使用する場合、同じ問題が発生します。

library(RWeka) 
BigramTokenizer <- function(x) NGramTokenizer(x, Weka_control(min = 3, max = 3)) 
tdm <- TermDocumentMatrix(oz, control = list(tokenize = BigramTokenizer)) 
inspect(tdm) 

答えて

2

問題は、デフォルトでは、そこにあるということですがあなたの条件を小文字にするDocumentTermMatrix()のオプション。これをオフにすると、あなたは大文字小文字を保持します。ここで

dtm <- DocumentTermMatrix(oz, control = list(tolower = FALSE)) 
colnames(dtm)[grep(".iami", colnames(dtm))] 
## [1] "Miami" "Miami," "Miami." "Miami’s" 

は、quantedaパッケージを使用してそれを行うための別の方法だより簡単かもしれません:

require(quanteda) 
# straight from text to the matrix 
dfmMatrix <- dfm(doctext, removeHyphens = TRUE, toLower = FALSE, 
       ignoredFeatures = stopwords("english"), verbose = FALSE) 
# gets frequency counts, sorted in descending order of total term frequency 
termfreqs <- topfeatures(dfmMatrix, n = nfeature(dfmMatrix)) 
# remove those with frequency < 2 
termfreqs <- termfreqs[termfreqs >= 2] 
head(termfreqs, 20) 
##  art   I  artists collecting   work   We collection collectors 
##  35   29   19   17   15   14   13   12 
##  What contemporary   The  world   us   It  Miami   one 
##  11   10   10   10   10   9   9   8 
## always   many   make   Art 
##  8   8   8   7 

私たちは、「マイアミ」(例えば)のためのケースが保存されていることを見ることができます。

termfreqs[grep(".iami", names(termfreqs))] 
## Miami Miami’s 
##  9  2 
+1

@Ken Benoitありがとうございました。パッケージのquantedaは素晴らしいようです。 – mql4beginner