我使用Nokogiri代碼來提取HTML節點之間的文本,並在讀取文件列表時獲取這些錯誤。我沒有使用簡單的嵌入式HTML獲取錯誤。我想消除或壓制警告,但不知道如何。這些警告都在每個塊的結尾:已經初始化常量警告
extract.rb:18: warning: already initialized constant EXTRACT_RANGES
extract.rb:25: warning: already initialized constant DELIMITER_TAGS
這裏是我的代碼:
#!/usr/bin/env ruby -wKU
require 'rubygems'
require 'nokogiri'
require 'fileutils'
source = File.open('/documents.txt')
source.readlines.each do |line|
line.strip!
if File.exists? line
file = File.open(line)
doc = Nokogiri::HTML(File.read(line))
# suggested by dan healy, stackoverflow
# Specify the range between delimiter tags that you want to extract
# triple dot is used to exclude the end point
# 1...2 means 1 and not 2
EXTRACT_RANGES = [
1...2
]
# Tags which count as delimiters, not to be extracted
DELIMITER_TAGS = [
"h1",
"h2",
"h3"
]
extracted_text = []
i = 0
# Change /"html"/"body" to the correct path of the tag which contains this list
(doc/"html"/"body").children.each do |el|
if (DELIMITER_TAGS.include? el.name)
i += 1
else
extract = false
EXTRACT_RANGES.each do |cur_range|
if (cur_range.include? i)
extract = true
break
end
end
if extract
s = el.inner_text.strip
unless s.empty?
extracted_text << el.inner_text.strip
end
end
end
end
print("\n")
puts line
print(",\n")
# Print out extracted text (each element's inner text is separated by newlines)
puts extracted_text.join("\n\n")
end
end
您是否嘗試將常量重命名爲EXTRACT_RANGES/DELIMITER_TAGS之外的其他東西? –
是的,我重命名了常量,並且我得到了相同的警告,只是反映了新的名字。 – chuckfinley
這個問題與Nokogiri無關,它是「我應該在哪裏定義一個恆定的問題」,所以我刪除了Nokogiri標籤並調整了標題。 –