微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用自定义分隔符将语料库分成段落

如何解决如何使用自定义分隔符将语料库分成段落

我正在抓取纽约时报的网页以对其进行一些自然语言处理,我想在使用语料库时将网页拆分为多个段落,以便对出现在段落中且包含关键词或短语的单词进行频率计数.

以下适用于句子,但段落是由纽约时报的 • 捐赠的,所以我需要将其替换为语料库阅读段落的方式 - 有人知道吗?我试过 gsub("•","/n",...) 和 gsub("•","/r/n") 但这没有用。

如果有人知道如何在 tm 语料库中完成这一切,而不必在 quanteda 和 TM 之间切换,这样可以节省一些代码

 website<-read_html("https://www.nytimes.com/2017/01/03/briefing/asia-australia-briefing.html") #Read URL
     


  #Obtain any text with the paragraph Html deliminator 
  text<-website%>%
    html_nodes("p") %>%
    html_text() %>% as.character()
  
  #Collapse the string as it is currently text[1]=para1 and text[2]= para 2
  text<- str_c(text,collapse=" ")


data_corpus_para <- 
  corpus_reshape(corpus((text),to="paragraphs"))


data_corpus_para <-tolower(data_corpus_para )


containstarget <- 
  stringr::str_detect(texts(data_corpus_para ),"pull out of peace talks") #Random string in only one of the paragraphs to proof concept

#Filter for the para's that only contain the sentence above
data_corpus_para <- 
  corpus_subset(data_corpus_para,containstarget)                 

data_corpus_para <-corpus_reshape(data_corpus_para,to = "documents")


#There are quanteda corpus and TM Corpuses. And so I have to convert to a dataframe and then make back into a vcorupus.. this is very messy

data_corpus_para <-quanteda::convert(data_corpus_para )
data_corpus_para_VCorpus<-tm::VCorpus(tm::VectorSource(data_corpus_para$text))

dt.dtm = tm::DocumentTermMatrix(data_corpus_para_VCorpus)
tm::findFreqTerms(dt.dtm,1)

解决方法

如果段落分隔符是“•”,则可以使用corpus_segment()

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.

txt <- "
• This is the first paragraph.
This is still the first paragraph.
• Here is the third paragraph.  Last sentence"

corpus(txt) %>%
  corpus_segment(pattern = "•")
## Corpus consisting of 2 documents and 1 docvar.
## text1.1 :
## "This is the first paragraph. This is still the first paragra..."
## 
## text1.2 :
## "Here is the third paragraph.  Last sentence"

reprex package (v1.0.0) 于 2021 年 4 月 10 日创建

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?