文档术语矩阵在语料库参数上出错。

56
我有以下代码:

# returns string w/o leading or trailing whitespace
trim <- function (x) gsub("^\\s+|\\s+$", "", x)

news_corpus <- Corpus(VectorSource(news_raw$text)) # a column of strings.

corpus_clean <- tm_map(news_corpus, tolower)
corpus_clean <- tm_map(corpus_clean, removeNumbers)
corpus_clean <- tm_map(corpus_clean, removeWords, stopwords('english'))
corpus_clean <- tm_map(corpus_clean, removePunctuation)
corpus_clean <- tm_map(corpus_clean, stripWhitespace)
corpus_clean <- tm_map(corpus_clean, trim)

news_dtm <- DocumentTermMatrix(corpus_clean) # errors here

当我运行DocumentTermMatrix()方法时,它给了我这个错误:

Error: inherits(doc, "TextDocument") is not TRUE

为什么会出现这个错误?我的行不是文本文档吗?
在检查corpus_clean后,这是输出结果:
[[153]]
[1] obama holds technical school model us

[[154]]
[1] oil boom produces jobs bonanza archaeologists

[[155]]
[1] islamic terrorist group expands territory captures tikrit

[[156]]
[1] republicans democrats feel eric cantors loss

[[157]]
[1] tea party candidates try build cantor loss

[[158]]
[1] vehicles materials stored delaware bridges

[[159]]
[1] hill testimony hagel defends bergdahl trade

[[160]]
[1] tweet selfpropagates tweetdeck

[[161]]
[1] blackwater guards face trial iraq shootings

[[162]]
[1] calif man among soldiers killed afghanistan

[[163]]
[1] stocks fall back world bank cuts growth outlook

[[164]]
[1] jabhat alnusra longer useful turkey

[[165]]
[1] catholic bishops keep focus abortion marriage

[[166]]
[1] barbra streisand visits hill heart disease

[[167]]
[1] rand paul cantors loss reason stop talking immigration

[[168]]
[1] israeli airstrike kills northern gaza

编辑:这是我的数据:

type,text
neutral,The week in 32 photos
neutral,Look at me! 22 selfies of the week
neutral,Inside rebel tunnels in Homs
neutral,Voices from Ukraine
neutral,Water dries up ahead of World Cup
positive,Who's your hero? Nominate them
neutral,Anderson Cooper: Here's how
positive,"At fire scene, she rescues the pet"
neutral,Hunger in the land of plenty
positive,Helping women escape 'the life'
neutral,A tour of the sex underworld
neutral,Miss Universe Thailand steps down
neutral,China's 'naked officials' crackdown
negative,More held over Pakistan stoning
neutral,Watch landmark Cold War series
neutral,In photos: History of the Cold War
neutral,Turtle predicts World Cup winner
neutral,What devoured great white?
positive,Nun wins Italy's 'The Voice'
neutral,Bride Price app sparks debate
neutral,China to deport 'pork' artist
negative,Lightning hits moving car
neutral,Singer won't be silenced
neutral,Poland's mini desert
neutral,When monarchs retire
negative,Murder on Street View?
positive,Meet armless table tennis champ
neutral,Incredible 400 year-old globes
positive,Man saves falling baby
neutral,World's most controversial foods

我获取的方式如下:

news_raw <- read.csv('news_csv.csv', stringsAsFactors = F)

编辑:这是traceback()的内容:

> news_dtm <- DocumentTermMatrix(corpus_clean)
Error: inherits(doc, "TextDocument") is not TRUE
> traceback()
9: stop(sprintf(ngettext(length(r), "%s is not TRUE", "%s are not all TRUE"), 
       ch), call. = FALSE, domain = NA)
8: stopifnot(inherits(doc, "TextDocument"), is.list(control))
7: FUN(X[[1L]], ...)
6: lapply(X, FUN, ...)
5: mclapply(unname(content(x)), termFreq, control)
4: TermDocumentMatrix.VCorpus(x, control)
3: TermDocumentMatrix(x, control)
2: t(TermDocumentMatrix(x, control))
1: DocumentTermMatrix(corpus_clean)

当我评估inherits(corpus_clean, "TextDocument")时,它是FALSE。

1
如果我使用 data(crude); news_corpus <- crude; 然后运行所有的转换,我就不会出现错误。news_raw$text 到底是什么样子?它属于哪个类别? - MrFlick
1
实际上,“character”是正确的。那只是R称呼它的方式。其他编程语言可能称之为字符串。但就目前而言,如果没有数据,我无法重现您的问题。您能否提供一个最小化可复制的示例,以便我可以运行并得到相同的错误? - MrFlick
1
你还是会收到错误吗?我想添加traceback()的结果应该能够确定发生错误的(子)函数。在你收到错误后运行该命令即可。 - MrFlick
回溯信息显示错误最终发生在“termFreq”函数中。再问你一件事,执行“table(sapply(corpus_clean, class))”会返回什么?你尝试过不进行“trim”步骤吗? - MrFlick
1
那是个问题。你确保代码完全按照上面的方式运行了吗?Corpus(VectorSource(news_raw$text))应该将所有内容转换为纯文本文档。当我运行sapply( ,class)时,我得到了character, PlainTextDocument, TextDocument - MrFlick
显示剩余8条评论
4个回答

125
似乎在tm 0.5.10版本中可以正常工作,但是在tm 0.6.0版本中发生了变化,导致它无法正常工作。问题在于tolowertrim函数不一定返回TextDocuments(看起来旧版本可能已经自动进行了转换)。相反,它们返回字符,而DocumentTermMatrix不确定如何处理这样的字符语料库。
因此,您可以更改为

corpus_clean <- tm_map(news_corpus, content_transformer(tolower))

或者你可以运行

corpus_clean <- tm_map(corpus_clean, PlainTextDocument)

在所有非标准转换(不包括getTransformations()中的转换)完成之后,在创建DocumentTermMatrix之前执行此操作。这应该确保您的所有数据都以PlainTextDocument格式存在,并且应该使DocumentTermMatrix工作正常。


为什么tm的作者们总是破坏向后兼容性?不到一个月前又发生了这种情况,其中涉及到readerControl。 - wordsforthewise

9
我在一篇关于TM的文章中找到了解决这个问题的方法。
以下是一个出现错误的示例:
getwd()
require(tm)
files <- DirSource(directory="texts/", encoding="latin1") # import files
corpus <- VCorpus(x=files) # load files, create corpus

summary(corpus) # get a summary
corpus <- tm_map(corpus,removePunctuation)
corpus <- tm_map(corpus,stripWhitespace)
corpus <- tm_map(corpus,removePunctuation);
matrix_terms <- DocumentTermMatrix(corpus)

警告信息:

In TermDocumentMatrix.VCorpus(x, control) : 无效的文档标识符

这个错误是因为在进行词项-文档矩阵时需要使用 Vector Source 类的对象,但是之前的转换将你的文本语料库转换成字符形式,从而改变了一个不被该函数接受的类。

然而,如果在 tm_map 命令中添加 content_transformer 函数,则在使用 TermDocumentMatrix 函数之前甚至不需要再添加一条命令。

下面的代码更改了类(请参见倒数第二行),避免了错误:

getwd()
require(tm)
files <- DirSource(directory="texts/", encoding="latin1")
corpus <- VCorpus(x=files) # load files, create corpus

summary(corpus) # get a summary
corpus <- tm_map(corpus,content_transformer(removePunctuation))
corpus <- tm_map(corpus,content_transformer(stripWhitespace))
corpus <- tm_map(corpus,content_transformer(removePunctuation))
corpus <- Corpus(VectorSource(corpus)) # change class 
matrix_term <- DocumentTermMatrix(corpus)

1
请务必阅读如何格式化内容,并查看我在编辑中所做的。谢谢! - Andrew Barber
感谢您的编辑,安德鲁。由于在此日期之前我从未尝试过在这个论坛上发布帖子,所以有点困惑于这些说明。 - Rodrigo Araujo
我已经整理了这个答案,@RodrigoAraujo 请审核。答案应该尽可能简洁。 - hongsy

5

将其更改为:

corpus_clean <- tm_map(news_corpus, tolower)

对于这个问题:

corpus_clean <- tm_map(news_corpus, content_transformer(tolower))

1
请避免发布已经被回答过的解决方案。 - Hardik Gupta

0

这应该可以工作。

remove.packages(tm)
install.packages("http://cran.r-project.org/bin/windows/contrib/3.0/tm_0.5-10.zip",repos=NULL)
library(tm)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接