如何解决Quanteda - 从具有多个文档的数据帧创建语料库
这里是第一个问题,因此对任何失礼表示歉意。我在 R 中有一个包含 4 个变量的 657 个观察值的数据框。每一次观察都是澳大利亚总理的一次演讲或采访。所以变量是:
- 日期
- 标题
- 网址
- txt(演讲/采访全文)。
我正在尝试将其转换为 Quanteda 中的语料库
我第一次尝试了 corp <- corpus(all_content)
但它给了我一条错误消息
Error in corpus.data.frame(all_content) :
text_field column not found or invalid
虽然有效:corp <- corpus(paste(all_content))
然后 summary(corp)
给了我
Corpus consisting of 4 documents,showing 4 documents:
Text Types Tokens Sentences
text1 243 1316 1
text2 1095 6523 3
text3 661 2630 1
text4 25243 1867648 62572
我的理解是,这样做是有效地将每一列变成了一个文档,而不是每一行?
如果重要,txt
变量将保存为列表。用于创建每一行的代码是
```{r new_function}
scrape_speech <- function(url){
speech_page <- read_html(url)
date <- speech_page %>% html_nodes(".date-display-single") %>% html_text() %>% dmy()
title <- speech_page %>% html_nodes(".pagetitle") %>% html_text()
txt <- speech_page %>% html_nodes("#block-system-main p") %>% html_text() %>% list()
tibble (date = date,title = title,URL = url,txt=txt)}
然后我使用 map_dfr
函数遍历并抓取了 657 个单独的 URL。
有人向我建议这是因为 txt
已保存为列表。我尝试在函数中不使用 list()
并获得 21,904 个观察值,因为全文文档中的每个段落都变成了一个单独的观察值。我可以用 corp <- corpus(paste(all_content_not_list))
把它变成一个语料库(再一次,没有 paste
我得到和上面一样的错误)。这同样给了我语料库中的 4 个文档!
summary(corp)
给我
Corpus consisting of 4 documents,showing 4 documents:
Text Types Tokens Sentences
text1 243 43810 1
text2 1092 214970 25
text3 657 87618 1
text4 25243 1865687 62626
提前致谢 丹尼尔
解决方法
很难准确地解决这个问题,因为您的 data.frame 对象没有可重现的示例,但是如果结构包含您列出的变量,那么应该这样做:
corpus(all_content,text_field = "txt")
有关详细信息,请参阅 ?corpus.data.frame
。如果那不这样做,然后尝试将输出添加到您的问题
str(all_content)
以便我们可以更详细地查看您的 all_content
对象中的内容。
在 OP 添加新数据后进行了编辑:
好的,所以 txt
在您的 tibble 中是一个字符元素列表。您需要将这些组合成一个字符,以便将其用作 corpus.data.frame()
的输入。方法如下:
library("quanteda")
## Package version: 3.0.0
## Unicode version: 10.0
## ICU version: 61.1
## Parallel computing: 12 of 12 threads used.
## See https://quanteda.io for tutorials and examples.
dframe <- structure(list(
date = structure(18620,class = "Date"),title = " Prime Minister's Christmas Message to the ADF",URL = "https://www.pm.gov.au/media/prime-ministers-christmas-message-adf",txt = list(c(
"G'day and Merry Christmas to everyone in our Australian Defence Force.","You know,throughout our history,successive Australian governments... And this year was no different.","God bless."
))
),row.names = c(NA,-1L),class = c("tbl_df","tbl","data.frame")
)
dframe$txt <- vapply(dframe$txt,paste,character(1),collapse = " ")
corp <- corpus(dframe,text_field = "txt")
print(corp,max_nchar = -1)
## Corpus consisting of 1 document and 3 docvars.
## text1 :
## "G'day and Merry Christmas to everyone in our Australian Defence Force. You know,successive Australian governments... And this year was no different. God bless."
由 reprex package (v1.0.0) 于 2021 年 4 月 8 日创建
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。