sgmllib

ตัวอย่างโค๊ดไพธอน ในการใช้งานมอดูล sgmllib เอามาใช้ในการจัดลำดับน้ำหนักให้กับเนื้อความใน HTML
โดยจะวิเคราะห์น้ำหนักจากแท็ก
(จุดประสงค์ที่แท้จริง คือจะเอาน้ำหนักนี้มาจัดลำดับความสำคัญในการค้นหาข้อมูล) เขียนโดยเอาตัวอย่างจาก เวลาใช้งานจะเอาตัวแปร self.data_line ไปใช้
ตัวอย่างการใช้งานคือ
กรณีข้อความธรรมดา
>>> import util
>>> data_list = util.HTML_weight_parse('This is the example of sgmllib.')
>>> data_list.data_line
[['This is the example of sgmllib.', 1]]
กรณีเป็นไฟล์ HTML
สมมุติว่าเนื้อไฟล์ test.html คือ



  abc



  this is x.html
  testlink



การใช้งานจะเป็นดังนี้
>>> import util
>>> f = open('test.html')
>>> data_list = util.HTML_weight_parse(f.read())
>>> data_list.data_line
[['abc', 11], ['this is x.html', 1], ['abc.com', 11], ['testlink', 11]]
เนื้อไฟล์ util.py มีดังนี้
#!/usr/bin/env python

import sgmllib

class HTML_weight_parse(sgmllib.SGMLParser):
    """Determine weight of text in HTML.
    input: text or html
    output = self.data_line : [[line1, weight1], ...]

    tag omitted data:
        script, style

    tag included attribute:
        meta name="keywords" content="..."
        img src="..." title="..." alt="..."
        a href="..."
    """

    weight_dict = { 'title':10, 'h1':10, 'h2':8, 'h3':7, 'h4':6, 'h5':5, 'h6':4 }

    def __init__(self, text):
        self.data = ''
        self.weight = 1
        self.data_line = []
        sgmllib.SGMLParser.__init__(self)
        for line in text.split('\n'):
            self.feed(line.strip())
        self.close()

    def handle_data(self, data):
        self.data += data

    def handle_comment(self, data): #bypass comment 
        pass

    def start_script(self, data): #bypass 
        pass

    def unknown_starttag(self, tag, attrs):
        self.flush()
        if attrs:  #tag with attributes
            meta_enable = False
            for name, value in attrs:
                if tag == "a":
                    if name == "href":
                       self.data += value
                       self.flush(False)
                elif tag == "meta":
                    if name == "name" and value == "keyword":
                        meta_enable = True
                        self.weight += 2
                    if name == "content" and meta_enable:
                        self.data += value
                        self.flush(False)
                        meta_enable = False
                elif tag == "img" and name in ["title", "alt"]:
                    self.data += value
                    self.flush(False)
                else:
                    self.flush()
        #tag with & without attribute
        if tag in self.weight_dict.keys():
            self.weight += self.weight_dict[tag]
        else:
            self.flush()

    def unknown_endtag(self, tag):
        self.flush()

    def close(self):
        sgmllib.SGMLParser.close(self)
        self.flush()
Topic: