R:每学期查找频率 - 警告信息

时间:2015-10-19 19:40:37

标签: r frequency tm corpus term-document-matrix

我试图在Martin Luther King的“我有一个梦想”演讲中找到每个词的频率。我已将所有大写字母转换为小写,并删除了所有停用词。我在.txt文件中有文本,所以我不能在这里显示它。读入文件的代码如下:

 speech <- readLines(speech.txt)

然后我成功执行了转换为小写并删除了停用词并调用它:

 clean.speech 

现在我在查找每学期的频率方面遇到了一些问题。我创建了一个语料库,检查了我的语料库,并创建了一个TermDocumentMatrix,如下所示:

 myCorpus <- Corpus(VectorSource(clean.speech))
 inspect(myCorpus)
 TDM <- TermDocumentMatrix(myCorpus)

到目前为止一切都很好。但是,我编写了以下代码并收到了警告信息:

 m < as.matrix(TDM)

 Warning Message:
 "In m < as.matrix(TDM): longer object length is not a multiple of shorter  object length

我知道这是一个非常常见的警告信息,因此我首先使用Google搜索,但我找不到任何与术语频率有关的内容。我继续运行以下文本,看看它是否会带有警告消息,但它没有。

 v <- sort(rowSums(m), decreasing = TRUE)
 d <- data.frame(word=names(v), freq=v)
 head(d, 15)

我的目标只是找到术语的频率。我真诚地为提出这个问题而道歉,因为我知道这个问题被问了很多。我只是不明白我的代码有什么变化。谢谢大家,我很感激!

2 个答案:

答案 0 :(得分:1)

如果您的目标只是查找条款的频率,请尝试此操作。

首先,我得到了#34;我有一个梦想&#34;演讲到角色矢量:

# get the text of the speech from an HTML source, and extract the text
library(XML)
doc.html <- htmlTreeParse('http://www.analytictech.com/mb021/mlk.htm', useInternal = TRUE)
doc.text = unlist(xpathApply(doc.html, '//p', xmlValue))
doc.text = paste(doc.text, collapse = ' ')

然后,我在 quanteda 中创建文档术语矩阵,删除停用词(并添加&#34;将&#34;因为quanteda&#39; s内置英语停用词列表不包括这个术语)。从那里topfeatures()为您提供最常用的条款及其数量。

library(quanteda)
# create a document-feature matrix
IHADdfm <- dfm(doc.text, ignoredFeatures = c("will", stopwords("english")), verbose = FALSE)
# 12 most frequent features
topfeatures(IHADdfm, 12)
## freedom      one     ring    dream      let      day    negro    today     able    every together    years 
##      13       12       12       11       10        9        8        7        7        7        6        5 
# a word cloud, if you wish
plot(IHADdfm, random.order = FALSE)

enter image description here

答案 1 :(得分:0)

只需致电findFreqTerms(),例如为tm::findFreqTerms(TDM, lowfreq=2, highfreq = 5)

tm::是可选的 - 只是说它是tm包的内置函数)

相关问题