作为XPath专家,这是一个简单的点! :)
文档结构:
<tokens>
<token>
<word>Newt</word><entityType>PROPER_NOUN</entityType>
</token>
<token>
<word>Gingrich</word><entityType>PROPER_NOUN</entityType>
</token>
<token>
<word>admires</word><entityType>VERB</entityType>
</token>
<token>
<word>Garry</word><entityType>PROPER_NOUN</entityType>
</token>
<token>
<word>Trudeau</word><entityType>PROPER_NOUN</entityType>
</token>
</tokens>
忽略文档的语义概率,我想要提取出 [["Newt", "Gingrich"], ["Garry", "Trudeau"]],即:当有两个连续的标记其实体类型为PROPER_NOUN时,我想从这两个标记中提取单词。
我已经完成了以下步骤:
"//token[entityType='PROPER_NOUN']/following-sibling::token[1][entityType='PROPER_NOUN']"
... 我已经找到了两个连续的PROPER_NOUN标记中的第二个,但我不确定如何使其与第一个标记一起输出。
一些注释:
- 如果在NodeSets中有三个或更多连续的PROPER_NOUN标记(称为A,B,C),最好能够发出[A,B],[B,C]。
- 如果需要更高级别的处理NodeSets(例如在Ruby / Nokogiri中),我不介意,只要简化问题即可。
更新
这是我的解决方案,使用更高级别的Ruby函数。 但我厌倦了所有那些XPath恶棍踢沙子在我的脸上,我想知道真正的XPath编码者是如何做到的!
def extract(doc)
names = []
sentences = doc.xpath("//tokens")
sentences.each do |sentence|
tokens = sentence.xpath("token")
prev = nil
tokens.each do |token|
name = token.xpath("word").text if token.xpath("entityType").text == "PROPER_NOUN"
names << [prev, name] if (name && prev)
prev = name
end
end
names
end