向文本元素添加空格 [英] Adding whitespace to text elements

查看:168
本文介绍了向文本元素添加空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以将空格添加到每个包含文本的元素中? 对于此示例:

is there a way to add whitespace to each elements that contain text? For this example:

movie <- read_html("http://www.imdb.com/title/tt1490017/") 
cast <- html_nodes(movie, "#titleCast span.itemprop")
cast %>% html_structure()
[[1]]
<span.itemprop [itemprop]>
  {text}

[[2]]
<span.itemprop [itemprop]>
  {text}

我想使用html_text()之前的每个文本元素中添加尾随空格.我还有另一个用例,我想在文档层次结构中使用更高的html_text().结果是将多个文本合并到一个向量元素中.这样就无法推断相应部分的开始和结束.

I would want to add a trailing whitespace to each text element before using html_text(). I have another use case where I want to use html_text() higher up in the document hierarchy. The result is that several texts get combined within one vector element. This makes it impossible to infer start and end of the corresponding parts.

推荐答案

您的意思是这样的吗?

doc <- minimal_html("Hello<p>World</p>") 
doc %>% html_text # HelloWorld
doc %>% html_text_collapse(" ") # Hello World

如果是的话,下面是代码:

If so here is the code:

require(stringi)
require(rvest)

html_text_collapse <- function(x, collapse = " ", trim = TRUE){
  text <- html_text(html_nodes(x, xpath = ".//text()[normalize-space()]"))
  if (trim) {
    text <- stri_trim_both(text)
  }
  paste(text, collapse = collapse)
}

这篇关于向文本元素添加空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆