作为对Python regular expression的响应,我尝试使用HTMLParser实现一个HTML解析器:import HTMLParser
class ExtractHeadings(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.text = None
self.headings = []
def is_relevant(self, tagname):
return tagname == 'h1' or tagname == 'h2'
def handle_starttag(self, tag, attrs):
if self.is_relevant(tag):
self.in_heading = True
self.text = ''
def handle_endtag(self, tag):
if self.is_relevant(tag):
self.headings += [self.text]
self.text = None
def handle_data(self, data):
if self.text != None:
self.text += data
def handle_charref(self, name):
if self.text != None:
if name[0] == 'x':
self.text += chr(int(name[1:], 16))
else:
self.text += chr(int(name))
def handle_entityref(self, name):
if self.text != None:
print 'TODO: entity %s' % name
def extract_headings(text):
parser = ExtractHeadings()
parser.feed(text)
return parser.headings
print extract_headings('abdk3
The content we need
aaaaabbbThe content we need2
')print extract_headings('before
Hello
after')我想知道这个模块的API是坏的还是我没有注意到一些重要的事情。我的问题是:为什么我的handle_charref的实现必须如此复杂?{cd4{I>作为一个预期的为什么handle_charref的默认实现不使用适当的字符串调用handle_data?在
为什么没有我可以调用的handle_entityref的实用程序实现?它可以命名为handle_entityref_HTML4,它将查找html4中定义的实体,然后对它们调用handle_data。在
如果提供了这个API,编写定制的HTML解析器就会容易得多。我的误解在哪里?在