OSDN Git Service

e025f6cd46124882b6506b10f0359760c1428beb
[fukui-no-namari/fukui-no-namari.git] / src / Hage1 / barehtmlparser.py
1 # Copyright (C) 2006 by Aiwota Programmer
2 # aiwotaprog@tetteke.tk
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
18 from HTMLParser import HTMLParser
19 import htmlentitydefs
20
21
22 class BareHTMLParser(HTMLParser):
23     """Parses html by the minimal necessity
24
25     to_out_func format is:
26     def some_func(untied_data, is_bold, href):
27     where untied_data is non markuped string
28     and is_bold is whether untied_data is bold or not
29     and href is url anchor if exists
30     """
31
32     def __init__(self, to_out_func):
33         HTMLParser.__init__(self)
34         self.to_out_func = to_out_func
35         self.bold = False
36         self.href = None
37
38     def reset_func(self, to_out_func):
39         self.to_out_func = to_out_func
40
41     def to_out(self, data):
42         self.to_out_func(data, self.bold, self.href)
43
44     # handle_* are overriden methods
45
46     def handle_starttag(self, tag, attr):
47         if tag == "b":
48             self.bold = True
49         elif tag == "br":
50             self.to_out("\n")
51         elif tag == "a":
52             for item in attr:
53                 if item[0] == "href":
54                     self.href = item[1]
55
56     def handle_endtag(self, tag):
57         if tag == "b":
58             self.bold = False
59         elif tag == "a":
60             self.href = None
61
62     def handle_data(self, data):
63         self.to_out(data)
64
65     def handle_charref(self, ref):
66         data = None
67         try:
68             data = unichr(int(ref))
69         except:
70             data = "&#"+ref+";"
71         self.to_out(data)
72
73     def handle_entityref(self, name):
74         if name in htmlentitydefs.name2codepoint:
75             codepoint = htmlentitydefs.name2codepoint[name]
76             self.to_out(unichr(codepoint))
77         else:
78             self.to_out("&"+name+";")