Author Topic: HTML parser in Lua  (Read 14802 times)

0 Members and 1 Guest are viewing this topic.

Offline bastya_elvtars

  • Forum God
  • ****
  • Posts: 3 725
  • Karma: +173/-7
  • The rock n' roll doctor
    • The FreshStuff3 Site
HTML parser in Lua
« on: 20 June, 2007, 15:58:15 »
Suggestions, fixes, additions and any other types of feedback are welcome. :-)
Code: [Select]
--[[
HTML Parser in Lua
Inspired by this C# code:
http://www.codeproject.com/useritems/HTML_to_Plain_Text.asp

It does exactly the same as described there.
Only converts offline files.

Distributed under a modified BSD license, see at the end of the file
]]

-- What is the desired newline?
nl = "\n"

filename = "Y:/news.html"

function HTML_ToText (file)
  -- Declare variables, load the file. Make tags lowercase.
  local text
  local f=io.open (file)
  if f then
    text = f:read ("*a")
    f:close()
  end
  text = string.gsub (text,"(%b<>)",
  function (tag)
    return tag:lower()
  end)
  --[[
  First we kill the developer formatting (tabs, CR, LF)
  and produce a long string with no newlines and tabs.
  We also kill repeated spaces as browsers ignore them anyway.
  ]]
  local devkill=
    {
      ["("..string.char(10)..")"] = " ",
      ["("..string.char(13)..")"] = " ",
      ["("..string.char(15)..")"] = "",
      ["(%s%s+)"]=" ",
    }
  for pat, res in pairs (devkill) do
    text = string.gsub (text, pat, res)
  end
  -- Then we remove the header. We do this by stripping it first.
  text = string.gsub (text, "(<%s*head[^>]*>)", "<head>")
  text = string.gsub (text, "(<%s*%/%s*head%s*>)", "</head>")
  text = string.gsub (text, "(<head>,*<%/head>)", "")
  -- Kill all scripts. First we nuke their attribs.
  text = string.gsub (text, "(<%s*script[^>]*>)", "<script>")
  text = string.gsub (text, "(<%s*%/%s*script%s*>)", "</script>")
  text = string.gsub (text, "(<script>,*<%/script>)", "")
  -- Ok, same for styles.
  text = string.gsub (text, "(<%s*style[^>]*>)", "<style>")
  text = string.gsub (text, "(<%s*%/%s*style%s*>)", "</style>")
  text = string.gsub (text, "(<style>.*<%/style>)", "")
 
  -- Replace <td> with tabulators.
  text = string.gsub (text, "(<%s*td[^>]*>)","\t")
 
  -- Replace <br> with linebreaks.
  text = string.gsub (text, "(<%s*br%s*%/%s*>)",nl)
 
  -- Replace <li> with an asterisk surrounded by 2 spaces.
  -- Replace </li> with a newline.
  text = string.gsub (text, "(<%s*li%s*%s*>)"," *  ")
  text = string.gsub (text, "(<%s*/%s*li%s*%s*>)",nl)
 
  -- <p>, <div>, <tr>, <ul> will be replaced to a double newline.
    text = string.gsub (text, "(<%s*div[^>]*>)", nl..nl)
    text = string.gsub (text, "(<%s*p[^>]*>)", nl..nl)
    text = string.gsub (text, "(<%s*tr[^>]*>)", nl..nl)
    text = string.gsub (text, "(<%s*%/*%s*ul[^>]*>)", nl..nl)
  --
 
  -- Nuke all other tags now.
  text = string.gsub (text, "(%b<>)","")
 
  -- Replace entities to their correspondant stuff where applicable.
  -- C# is owned badly here by using a table. :-P
  -- A metatable secures entities, so you can add them natively as keys.
  -- Enclosing brackets also get added automatically (capture!)
  local entities = {}
  setmetatable (entities,
  {
    __newindex = function (tbl, key, value)
      key = string.gsub (key, "(%#)" , "%%#")
      key = string.gsub (key, "(%&)" , "%%&")
      key = string.gsub (key, "(%;)" , "%%;")
      key = string.gsub (key, "(.+)" , "("..key..")")
      rawset (tbl, key, value)
    end
  })
  entities =
  {
    ["&nbsp;"] = " ",
    ["&bull;"] = " *  ",
    ["&lsaquo;"] = "<",
    ["&rsaquo;"] = ">",
    ["&trade;"] = "(tm)",
    ["&frasl;"] = "/",
    ["&lt;"] = "<",
    ["&gt;"] = ">",
    ["&copy;"] = "(c)",
    ["&reg;"] = "(r)",
    -- Then kill all others.
    -- You can customize this table if you would like to,
    -- I just got bored of copypasting. :-)
    -- http://hotwired.lycos.com/webmonkey/reference/special_characters/
    ["%&.+%;"] = "",
  }
  for entity, repl in pairs (entities) do
    text = string.gsub (text, entity, repl)
  end
 
  return text
 
end

--[[
Copyright (c) 2007, bastya_elvtars

All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this
      list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of contributors may be used
      to endorse or promote products derived from this code without specific
      prior written permission.

THIS CODE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
CODE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]][/code ]

Wow:
Code: [Select]
  SHOUTcast Administrator

U SHOUTcast D.N.A.S. Status

SHOUTcast Server Version 1.9.5/Linux



Status | Song History | Listen | Stream URL | Admin Login

Current Stream Information

Server Status: Server is currently up and public.

Stream Status: Stream is up at 64 kbps with 117 of 200 listeners (117 unique)

Listener Peak: 176

Average Listen Time: 4h 17m 46s

Stream Title: MAGNATUNE.COM Classical: renaissance and baroque (try before you buy)

Content Type: audio/mpeg

Stream Genre: Classical Instrumental Symphonic Contemporary Renaissance Baroque Medieval

Stream URL: http://magnatune.com/genres/classical/

Stream ICQ:

Stream AIM:

Stream IRC:

Current Song: 06-Cesses mortels de soupirer (Pierre Guedron)-Orinda_spoken



Written by Stephen 'Tag Loomis, Tom Pepper and Justin Frankel

Copyright Nullsoft Inc. 1998-2004[/quote]
Everything could have been anything else and it would have just as much meaning.

PtokaX forum

HTML parser in Lua
« on: 20 June, 2007, 15:58:15 »

Offline achiever

  • Lord
  • ***
  • Posts: 260
  • Karma: +25/-22
Re: HTML parser in Lua
« Reply #1 on: 20 June, 2007, 20:43:41 »
bastya where does the text file of this gets stored? or does it stores it at all?
i couldnt find how it work, so i asked.
thks,
achiever.

Offline bastya_elvtars

  • Forum God
  • ****
  • Posts: 3 725
  • Karma: +173/-7
  • The rock n' roll doctor
    • The FreshStuff3 Site
Re: HTML parser in Lua
« Reply #2 on: 20 June, 2007, 20:54:19 »
This does not work with PtokaX. This is just code for incorporation into a proper script.
Everything could have been anything else and it would have just as much meaning.

Offline achiever

  • Lord
  • ***
  • Posts: 260
  • Karma: +25/-22
Re: HTML parser in Lua
« Reply #3 on: 20 June, 2007, 21:11:02 »
ok
thks,
achiever.

Offline Yahoo

  • Triple Ace
  • **
  • Posts: 225
  • Karma: +32/-14
  • People Say "I Dont Know English"
    • Yahoo
Re: HTML parser in Lua
« Reply #4 on: 29 June, 2007, 06:40:40 »
hello, how to use this script??
"BoRN FIGhTEr"

Offline bastya_elvtars

  • Forum God
  • ****
  • Posts: 3 725
  • Karma: +173/-7
  • The rock n' roll doctor
    • The FreshStuff3 Site
Re: HTML parser in Lua
« Reply #5 on: 27 July, 2007, 03:21:46 »
This does not work with PtokaX. This is just code for incorporation into a proper script.

Hi all, here comes an updated version. It parses a tags as well, and collects links as endnotes. It parses http://www.lua.org/ in the following way:
Code: [Select]
  The Programming Language Lua       

    ? about[1] ? news[2] ? download[3] ? documentation[4] ? community[5] ? site map[6] ? portuguęs[7] ? contact[8] ? rss[9]

   

 

 

       Lua 5.1.2[10] released, fixing all known bugs in Lua 5.1[11].

   Korean translation[12] of Programming in Lua published.

   

--

[1]http://www.lua.org/about.html
[2]http://www.lua.org/news.html
[3]http://www.lua.org/download.html
[4]http://www.lua.org/docs.html
[5]http://www.lua.org/community.html
[6]http://www.lua.org/map.html
[7]http://www.lua.org/portugues.html
[8]http://www.lua.org/contact.html
[9]http://www.lua.org/rss.html
[10]http://www.lua.org/ftp/lua-5.1.2.tar.gz
[11]http://www.lua.org/bugs.html#5.1.1
[12]http://insightbook.springnote.com/pages/253177

Here is the updated snippet:

Code: Lua
  1. --[[
  2. HTML Parser in Lua
  3. Inspired by this C# code:
  4. http://www.codeproject.com/useritems/HTML_to_Plain_Text.asp
  5.  
  6. It does exactly the same as described there.
  7. Only converts offline files.
  8.  
  9. Distributed under a modified BSD license, see at the end of the file]]
  10.  
  11. -- What is the desired newline?
  12. nl = "\n"
  13.  
  14. filename = "E:/luaorg.htm"
  15.  
  16. function HTML_ToText (file)
  17.   -- Declare variables, load the file. Make tags lowercase.
  18.   local text
  19.   local f=io.open (file)
  20.   if f then
  21.     if f:seek("end") <= 0 then return end
  22.     f:seek("set")
  23.     text = f:read ("*a")
  24.     f:close()
  25.   end
  26.   text = string.gsub (text,"(<([^>]-)>)",function (str) return str:lower() end)
  27.   --[[
  28.   First we kill the developer formatting (tabs, CR, LF)
  29.   and produce a long string with no newlines and tabs.
  30.   We also kill repeated spaces as browsers ignore them anyway.
  31.   ]]
  32.   local devkill=
  33.     {
  34.       ["("..string.char(10)..")"] = " ",
  35.       ["("..string.char(13)..")"] = " ",
  36.       ["("..string.char(15)..")"] = "",
  37.       ["(%s%s+)"]=" ",
  38.     }
  39.   for pat, res in pairs (devkill) do
  40.     text = string.gsub (text, pat, res)
  41.   end
  42.   -- Then we remove the header. We do this by stripping it first.
  43.   text = string.gsub (text, "(<%s*head[^>]*>)", "<head>")
  44.   text = string.gsub (text, "(<%s*%/%s*head%s*>)", "</head>")
  45.   text = string.gsub (text, "(<head>,*<%/head>)", "")
  46.   -- Kill all scripts. First we nuke their attribs.
  47.   text = string.gsub (text, "(<%s*script[^>]*>)", "<script>")
  48.   text = string.gsub (text, "(<%s*%/%s*script%s*>)", "</script>")
  49.   text = string.gsub (text, "(<script>,*<%/script>)", "")
  50.   -- Ok, same for styles.
  51.   text = string.gsub (text, "(<%s*style[^>]*>)", "<style>")
  52.   text = string.gsub (text, "(<%s*%/%s*style%s*>)", "</style>")
  53.   text = string.gsub (text, "(<style>.*<%/style>)", "")
  54.  
  55.   -- Replace <td> and <th> with tabulators.
  56.   text = string.gsub (text, "(<%s*td[^>]*>)","\t")
  57.   text = string.gsub (text, "(<%s*th[^>]*>)","\t")
  58.  
  59.   -- Replace <br> with linebreaks.
  60.   text = string.gsub (text, "(<%s*br%s*%/%s*>)",nl)
  61.  
  62.   -- Replace <li> with an asterisk surrounded by spaces.
  63.   -- Replace </li> with a newline.
  64.   text = string.gsub (text, "(<%s*li%s*%s*>)"," *  ")
  65.   text = string.gsub (text, "(<%s*/%s*li%s*%s*>)",nl)
  66.  
  67.   -- <p>, <div>, <tr>, <ul> will be replaced to a double newline.
  68.   text = string.gsub (text, "(<%s*div[^>]*>)", nl..nl)
  69.   text = string.gsub (text, "(<%s*p[^>]*>)", nl..nl)
  70.   text = string.gsub (text, "(<%s*tr[^>]*>)", nl..nl)
  71.   text = string.gsub (text, "(<%s*%/*%s*ul[^>]*>)", nl..nl)
  72.    
  73.   -- Some petting with the <a> tags. :-P
  74.   local addresses,c = {},0
  75.   text=string.gsub(text,"<%s*a.-href=[\'\"](%S+)[\'\"][^>]*>(.-)<%s*%/*%s*a[^>]->", -- gets URL from a tag, and the enclosed name
  76.   function (url,name)
  77.     c = c + 1
  78.     name = string.gsub (name, "<([^>]-)>","") -- strip name from tags (e. g. images as links)
  79.    
  80.     -- We only consider the URL valid if the name contains alphanumeric characters.
  81.     if name:find("%w") then print(url, name, c) table.insert (addresses, {url, name}) return name.."["..#addresses.."]" else return "" end    
  82.   end)
  83.  
  84.   -- Nuke all other tags now.
  85.   text = string.gsub (text, "(%b<>)","")
  86.  
  87.   -- Replace entities to their correspondant stuff where applicable.
  88.   -- C# is owned badly here by using a table. :-P
  89.   -- A metatable secures entities, so you can add them natively as keys.
  90.   -- Enclosing brackets also get added automatically (capture!)
  91.   local entities = {}
  92.   setmetatable (entities,
  93.   {
  94.     __newindex = function (tbl, key, value)
  95.       key = string.gsub (key, "(%#)" , "%%#")
  96.       key = string.gsub (key, "(%&)" , "%%&")
  97.       key = string.gsub (key, "(%;)" , "%%;")
  98.       key = string.gsub (key, "(.+)" , "("..key..")")
  99.       rawset (tbl, key, value)
  100.     end
  101.   })
  102.   entities =
  103.   {
  104.     ["&nbsp;"] = " ",
  105.     ["&bull;"] = " *  ",
  106.     ["&lsaquo;"] = "<",
  107.     ["&rsaquo;"] = ">",
  108.     ["&trade;"] = "(tm)",
  109.     ["&frasl;"] = "/",
  110.     ["&lt;"] = "<",
  111.     ["&gt;"] = ">",
  112.     ["&copy;"] = "(c)",
  113.     ["&reg;"] = "(r)",
  114.     -- Then kill all others.
  115.     -- You can customize this table if you would like to,
  116.     -- I just got bored of copypasting. :-)
  117.     -- http://hotwired.lycos.com/webmonkey/reference/special_characters/
  118.     ["%&.+%;"] = "",
  119.   }
  120.   for entity, repl in pairs (entities) do
  121.     text = string.gsub (text, entity, repl)
  122.   end
  123. --   text = text..nl..nl..("-"):rep(27)..nl..nl
  124. --  
  125. --   for k,v in ipairs (addresses) do
  126. --     text = text.."["..k.."] "..v[1]..nl
  127. --   end
  128.   if #addresses > 0 then
  129.     text=text..nl:rep(2)..("-"):rep(2)..nl
  130.     for key, tbl in ipairs(addresses) do
  131.       text = text..nl.."["..key.."]"..tbl[1]
  132.     end
  133.   end
  134.  
  135.   return text
  136.  
  137. end
  138.  
  139. local f=io.open(filename..".txt", "w")
  140. f:write(HTML_ToText (filename))
  141. f:close()
  142. --[[
  143. Copyright (c) 2007, bastya_elvtars
  144.  
  145. All rights reserved.
  146.  
  147. Redistribution and use in source and binary forms, with or without modification,
  148. are permitted provided that the following conditions are met:
  149.  
  150.     * Redistributions of source code must retain the above copyright notice, this
  151.       list of conditions and the following disclaimer.
  152.     * Redistributions in binary form must reproduce the above copyright notice,
  153.       this list of conditions and the following disclaimer in the documentation
  154.       and/or other materials provided with the distribution.
  155.     * Neither the name of the author nor the names of contributors may be used
  156.       to endorse or promote products derived from this code without specific
  157.       prior written permission.
  158.  
  159. THIS CODE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  160. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  161. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  162. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  163. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  164. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  165. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  166. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  167. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  168. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  169. CODE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  170. ]]
Everything could have been anything else and it would have just as much meaning.

PtokaX forum

Re: HTML parser in Lua
« Reply #5 on: 27 July, 2007, 03:21:46 »