gpt4 book ai didi

r - XPath:选择没有类属性的元素

转载 作者:行者123 更新时间:2023-12-03 16:58:00 25 4
gpt4 key购买 nike

我正在尝试提取具有以下结构的文本:

<p class="id1"> Title or something </p>    
<p> Text text text </p>
<p> More text </p>
<p class="id2"> Something else </p>


当我使用时:

text_info <- xpathSApply(PARSED, "//p", xmlValue)


结果是:

[1] 'Title or something'
[2] 'Text text text'
[3] 'More text'
[4] 'Something else'


我只希望 <p>中的文本没有类:

[1] 'Text text text'
[2] 'More text'


我正在使用以下代码,但是要花很长时间,并且有很多文本:

text_info <- setdiff(xpathSApply(PARSED, "//p", xmlValue), xpathSApply(PARSED, "//p[@class]", xmlValue))


有没有一种方法可以仅使用一个xpathSApply来仅提取那些没有类的人?

最佳答案

您可以在XPath中使用not()

xpathSApply(doc, "//p[not(@class)]", xmlValue, trim = TRUE)
# [1] "Text text text" "More text"


这将选择没有class属性的元素。

数据:

library(XML)
doc <- htmlParse('<p class="id1"> Title or something </p>
<p> Text text text </p>
<p> More text </p>
<p class="id2"> Something else </p>')

关于r - XPath:选择没有类属性的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40664256/

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