gpt4 book ai didi

r - 向文本元素添加空格

转载 作者:行者123 更新时间:2023-12-02 09:21:51 24 4
gpt4 key购买 nike

有没有办法向每个包含文本的元素添加空格?对于这个例子:

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() 。结果是多个文本组合在一个向量元素内。这使得无法推断相应部分的开始和结束。

最佳答案

你的意思是这样吗?

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

如果是的话,代码如下:

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)
}

关于r - 向文本元素添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42003932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com