r语言 - 数据帧中列的段落缩进



我正在尝试网络抓取,并设法获得了新闻的标题和详细内容故事。 相同的代码是:

webpage <- read_html("https://www.rediff.com/sports")
headlines.node <- html_nodes(webpage,'.relative h2 a')
headlines <- html_text(headlines.node)
headlines <- str_squish(headlines)
links <- webpage %>% html_nodes(".relative h2 a") %>% 
html_attr("href")
content <- c()
for(i in 1:length(links)){
newslink <- links[i]
webpage <- read_html(newslink)
story.node <- html_nodes(webpage, "p")
story <-  html_text(story.node)
story <- str_squish(story)
content[i] <- paste(story, collapse = '')
}
df <- data.frame("Headlines"=headlines, "Main Content"=content)

但是,为了将新闻的详细内容存储在数据帧字段中,我不得不折叠页面的详细内容故事,如果没有它,它将返回:"在内容[i] <- 故事中: 要替换的项目数不是替换长度的倍数"(,因为它返回一个段落的多行数据。

collapse 参数创建了一个列,其中包含如下数据:

df$Main.Content[1] 

上面的行返回: [1] 新闻应用程序(免费(科利获得"板球精神"锣;印度的虚张声势的揭幕战选手罗希特·夏尔马(Rohit Sharma(周三因其令人难以置信的状态而被评为ICC的2019年ODI年度板球运动员,而英国全能选手本·斯托克斯(Ben Stokes(则获得了整体荣誉。印度队长维拉特·科利(Virat Kohli(被任命为ICC年度测试和ODI团队的队长,此外还因试图阻止球迷在椭圆形世界杯比赛中对史蒂夫·史密斯发出嘘声而获得"板球精神"奖。史密斯当时因篡改球而被停赛一年后重返国际板球赛场。英格兰世界杯冠军全能选手斯托克斯获得了最大的奖项 - 年度最佳球员的"加菲尔德爵士清醒奖杯",而澳大利亚快速投球手帕特康明斯被评为年度测试球员.印度接缝员迪帕克·查哈尔赢得了T20国际年度表现,澳大利亚的Marnus Labuschagne被评为年度新兴板球运动员,而苏格兰的Kyle Coetzer被宣布为年度副板球运动员.32岁的.和剩下的故事(这里不复制完整的东西。

我们丢失了段落缩进,文本看起来很乱。有什么方法可以维护每个链接的段落缩进并将其存储在数据帧的字段中?

示例:就像我点击时一样

df$Main.Content[1]

它应该返回一个干净的段落缩进文本,如下所示:

新闻应用程序(免费(科利获得"板球精神"锣;印度的虚张声势的揭幕战选手罗希特·夏尔马(Rohit Sharma(周三因其令人难以置信的状态而被评为ICC的2019年ODI年度板球运动员,而英国全能选手本·斯托克斯(Ben Stokes(则获得了整体荣誉。

印度队长维拉特·科利(Virat Kohli(被任命为ICC年度测试和ODI团队的队长,此外还因试图阻止球迷在椭圆形世界杯比赛中对史蒂夫·史密斯发出嘘声而获得"板球精神"奖。史密斯当时因篡改球而被停赛一年后重返国际板球赛场。

(等等。。。与原始页面相同(

我试图最好地解释我的要求。请询问这个问题是否不清楚。

一种方法是用换行符折叠story

library(rvest)
for(i in 1:length(links)){
newslink <- links[i]
webpage <- read_html(newslink)
story.node <- html_nodes(webpage, "p")
story <-  html_text(story.node)
story <- str_squish(story)
content[i] <- paste(story, collapse = 'nn')
}
df <- data.frame(Headlines=headlines,Main_Content=content, stringsAsFactors = FALSE)

,然后使用cat查看文本

cat(df$Main_Content[1])
#Diagnosed with a concussion, wicketkeeper Rishabh Pant will not travel 
#with #the Indian team to Rajkot for the second ODI against Australia.
#Pant didn't take the field for the second half of the first ODI in 
#Mumbai #on Tuesday after getting hit on the helmet while batting. He 
#remains under #observation.
#"Rishabh Pant will not be travelling to Rajkot today with other 
#members. He will join the team later," a BCCI source told PTI.
#"Normally 24 hours is the time to keep someone who has suffered concussion 
#under observation," he added.
#....

最新更新