You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将多个字符对象合并为单个字符对象(R语言rvest场景)

如何将R语言爬取的多元素字符向量合并为单个字符对象

你可以通过字符向量合并函数搭配引号清理来实现需求,以下是两种可行方案:

方案1:使用Base R原生函数

直接用paste()合并向量,同时用gsub()移除多余双引号:

library(rvest)

url <- "https://www.bbc.com/future/article/20220823-how-auckland-worlds-most-spongy-city-tackles-floods"

final <- url %>% 
  read_html() %>% 
  html_elements(".article__body-content p") %>% 
  html_text()

# 清理引号并合并为单个字符串,段落间用两个换行分隔
final_combined <- paste(gsub('"', '', final), collapse = "\n\n")

方案2:使用stringr包(更简洁)

如果已经安装了stringr包(tidyverse生态的一部分),可以用str_c()和str_remove_all()组合:

library(rvest)
library(stringr)

url <- "https://www.bbc.com/future/article/20220823-how-auckland-worlds-most-spongy-city-tackles-floods"

final <- url %>% 
  read_html() %>% 
  html_elements(".article__body-content p") %>% 
  html_text()

# 清理引号+合并
final_combined <- str_c(str_remove_all(final, '"'), collapse = "\n\n")

关键说明

  • html_text()返回的是字符向量而非列表,因此不需要unlist(),直接对向量做合并操作即可
  • gsub('"', '', final)/str_remove_all(final, '"'):移除每个段落文本中的双引号(对应示例里的"But that’s supposed to happen,"变为But that’s supposed to happen,)
  • collapse = "\n\n":指定段落之间用两个换行符分隔,和你期望的格式一致

执行后final_combined就是单个字符对象,完全符合你的输出要求。

内容的提问来源于stack exchange,提问作者stats_noob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 06:45:56