In this HTML Parser- Part 2 problem You are given an HTML code snippet of N lines. Your task is to print the single-line comments, multi-line comments, and the data.


HackerRank HTML Parser - Part 2 solution in python


Problem solution in Python 2 programming.

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_comment(self, data):
        if "\n" in data:
            print ">>> Multi-line Comment"
        else:
            print ">>> Single-line Comment"
        print data
    def handle_data(self, data):
        if len(data.strip())>0:
            print ">>> Data"
            print data

html = ""       
for i in range(int(raw_input())):
    html += raw_input().rstrip()
    html += '\n'
    
parser = MyHTMLParser()
parser.feed(html)
parser.close()


Problem solution in Python 3 programming.

from html.parser import HTMLParser
html = ""
class MyHTMLParser(HTMLParser):
    def handle_comment(self,data):
        if('\n' in data):
            print(">>> Multi-line Comment")
        else:
            print(">>> Single-line Comment")
        print(data)
    def handle_data(self,data):
        if(data != '\n'):
            print(">>> Data")
            print(data)
             
for i in range(int(input())):
    html += input().rstrip()
    html += '\n'
#print(html)    
parser = MyHTMLParser()
parser.feed(html)
parser.close()


Problem solution in pypy programming.

from HTMLParser import HTMLParser
class CustomHTMLParser(HTMLParser):
    def handle_comment(self, data):
        number_of_line = len(data.split('\n'))
        if number_of_line>1:
            print('>>> Multi-line Comment')
        else:
            print('>>> Single-line Comment')
        if data.strip():
            print(data)

    def handle_data(self, data):
        if data.strip():
            print(">>> Data")
            print(data)

parser = CustomHTMLParser()

n = int(input())

html_string = ''
for i in range(n):
    html_string += raw_input().rstrip()+'\n'
    
parser.feed(html_string)
parser.close()


Problem solution in pypy3 programming.

# Enter your code here. Read input from STDIN. Print output to STDOUT
from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_comment(self, data):
        lines = data.split("\r")
        if len(lines) > 1:
            print(">>> Multi-line Comment")
            for l in lines:
                print(l)
        else:
            print(">>> Single-line Comment")
            print(lines[0])

    def handle_data(self, data):
        if len(data.strip()) == 0:
            return
        print(">>> Data")
        lines = data.split("\r")
        for l in lines:
            if l.strip() != "":
                print(l)

n = int(input())
input_data =""
for _ in range(n):
    input_data += input()
parser = MyHTMLParser()
parser.feed(input_data)