我已经阅读了大量问题和解决方案,以确定这是否已在其他地方得到解答,但似乎我找到的所有内容都不是我想要的内容。
我有一个XML文档,其中包含数百个文本条目,每个条目还列出了一个URL。每个URL都是一个字符串(在标签内),以唯一的4位数字结尾。 XML文件的格式基本如下:
<entry>
[other content]
<id>http://www.URL.com/blahblahblah-1234</id>
[other content]
</entry>
我想基本上只列出数字列表中最后有特定数字的网址。我将所有数字放在一个数组中,值设置为字符串(numbers = ["1234", "8649", etc.]
)。我一直在使用nokogiri作为我脚本的其他部分,当我只查找特定的字符串时,我只使用include?
,这非常有效。但是,当我在&#34;数字&#34;中有数百个字符串时,我不确定如何自动执行此操作。阵列。这基本上是我在逻辑上需要发生的事情:
id = nokodoc.css("id")
id.each { |id|
hyperlink = id.text
if hyperlink.include?(numbers)
puts "yes!"
else
puts "no :("
end
}
显然这不起作用,因为include?
需要一个字符串,而我传递整个数组。 (例如,如果我执行include?(numbers[0])
,则可以使用。)我已经使用any?
尝试了此功能,但在这种情况下它似乎无效。
是否有我不知道的Ruby方法,可以告诉我任何中任何的数组中是否存在任何我循环的节点?如果有任何需要澄清的话,请告诉我 - 说出正确的问题往往是最困难的部分!
修改:作为旁注,我最终要删除所有与不结尾的链接相对应的条目,其中包含其中一个数字数组,即
if hyperlink.include? (any number from the array)
puts "this one is good"
else
id.parent.remove
所以我会以某种方式需要最终产品来保持与nokogiri的解析。
非常感谢你们提供任何和所有见解!
答案 0 :(得分:0)
你可以这样做:
numbers = ['1234', '8649', ..]
urls = nokodoc.css('id').map(&:text)
urls = urls.select { |url| numbers.any? { |n| url.include? n } }
但效率不高。如果你知道模式 - 提取数字,然后检查它是否在数组中。例如,如果它总是最后4位数:
numbers = ['1234', '8649', ..]
urls = nokodoc.css('id').map(&:text)
urls = urls.select { |url| numbers.include? url[-4..-1] }
<强>更新强>
对于问题的变化:
numbers = ['1234', '8649', ..]
nodes = nokodoc.css('id')
nodes.each do |node|
url = node.text
if numbers.any? { |n| url.include? n }
puts 'this one is good'
else
node.parent.remove
end
end