0

我试图在马丁路德金的“我有一个梦想”演讲中找到每个术语的频率。我已将所有大写字母转换为小写字母,并删除了所有停用词。我在 .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

我知道这是一个非常常见的警告信息,所以我先用谷歌搜索了它,但我找不到任何与术语频率有关的信息。我继续运行以下文本,看看它是否会运行并显示警告消息,但它没有。

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

我的目标只是找到术语的频率。我真诚地为提出这个问题道歉,因为我知道这个问题被问了很多。我只是不明白要对我的代码进行哪些更改。谢谢大家我很感激!

4

2 回答 2

1

如果您的目标只是找到术语的频率,那么试试这个。

首先,我将“我有一个梦想”的演讲放入一个字符向量中:

# 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中创建文档术语矩阵,删除停用词(并添加“will”,因为 quanteda 的内置英语停用词列表不包括该术语)。从那里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)

在此处输入图像描述

于 2015-10-23T06:19:04.597 回答
0

只需调用findFreqTerms(),例如 as tm::findFreqTerms(TDM, lowfreq=2, highfreq = 5)

(这tm::是可选的 - 只是说它是 tm包的内置功能)

于 2015-10-22T08:14:54.563 回答