I wrote this simple HTML parser in Ruby.
Basically I have a folder that has files. Every file has crawled web pages. The only addition within these files is before the HTML content there is a page metadata, #URL
is one of them.
What I am aiming is to have two files:
1)Will contain: currentURL, destinationURL, description
2)Will contain: currentURL, destinationURL, word, count
So if I did that for this current page and assuming that href that I am looking at is:
<a href="http://stackoverflow.com" title="professional and enthusiast programmers">Stack Overflow</a>
1st file would have
codereview,stackexchange.com, http://stackoverflow.com, Stack Overflow
2nd file would have
codereview,stackexchange.com, http://stackoverflow.com, Stack, 1
codereview,stackexchange.com, http://stackoverflow.com, Overflow, 2
However my code works really slow. It has been longer than an hour and still parsing a file with size of 31MB.
My code is:
beginning_time = Time.now
folder = "allParts/"
extension = "*.dat"
urlMet = "#URL:"
newLine = "\n"
files = Dir[folder+extension]
hrefTag = "<a href=\""
qtMark = "\""
descStart = "\">"
hrefEnd = "</a>"
firstOutput = "firstOut.txt"
secondOutput = "secondOut.txt"
File.open(firstOutput, 'w') {}
File.open(secondOutput, 'w') {}
countFile = 1
for file in files do
puts file + "#: "+countFile.to_s
countFile++
File.open(file, "r") do |f|
source = ""
f.each_line do |line|
dest = ""
desc = ""
if line.include? urlMet
source = line[/#{urlMet}(.*?)#{newLine}/m, 1]
end
if line.include? hrefTag
dest = line[/#{hrefTag}(.*?)#{qtMark}/m, 1]
descStIn = line.rindex(descStart)
descEndIn = line.rindex(hrefEnd)
desc = line[descStIn+2..descEndIn-1]
end
if (source != "" && dest != "")
occur = Hash.new(0)
mainEntry = "original-url=\"" + source +
"\", dest-url=\"" + dest + "\""
descEntry = ""
if (desc != nil && desc != "")
descEntry = ", desc=\"" + desc + "\""
words = desc.split(' ')
words.each { |word| occur[word] += 1 }
end
firstEntry = mainEntry+descEntry+"\n\n"
File.open(firstOutput, 'a') { |file|
file.write(firstEntry)
}
occur.each { |word, occurrance|
wordEntry = ", word=\"" + word +
"\", count=" + occurrance.to_s
secondEntry = mainEntry+wordEntry+"\n\n"
File.open(secondOutput, 'a') { |file|
file.write(secondEntry)
}
}
end
end
end
end
end_time = Time.now
puts "Time elapsed #{(end_time - beginning_time)} seconds"