Advertisement
RedstoneHair

Simple parsing of text formatting

Feb 20th, 2024
848
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | Software | 0 0
  1. from html.parser import HTMLParser
  2. from collections import deque
  3.  
  4. fonts = ['regular', 'bold', 'italic', 'bold_italic']
  5. colors = ['white', 'yellow']
  6. color_map = {
  7.     'attack': 'yellow',
  8. }
  9. gimmicks = ['solid']
  10.  
  11.  
  12. class AdvancedTextParser(HTMLParser):
  13.     def __init__(self):
  14.         super().__init__()
  15.         self.current_font = deque(fonts[0:1])
  16.         self.current_color = deque(colors[0:1])
  17.         self.current_gimmick = deque(gimmicks[0:1])
  18.         self.letters = []
  19.  
  20.     def handle_starttag(self, tag, attrs):
  21.         if tag in fonts:
  22.             if tag == 'italic' and 'bold' in self.current_font:
  23.                 self.current_font.append('bold_italic')
  24.             elif tag == 'bold' and 'italic' in self.current_font:
  25.                 self.current_font.append('bold_italic')
  26.             else:
  27.                 self.current_font.append(tag)
  28.         elif tag in colors:
  29.             self.current_color.append(tag)
  30.         elif tag in color_map:
  31.             self.current_color.append(color_map[tag])
  32.         elif tag in gimmicks:
  33.             self.current_gimmick.append(tag)
  34.  
  35.     def handle_endtag(self, tag):
  36.         if tag in fonts:
  37.             self.current_font.pop()
  38.         elif tag in colors:
  39.             self.current_color.pop()
  40.         elif tag in color_map:
  41.             self.current_color.pop()
  42.         elif tag in gimmicks:
  43.             self.current_gimmick.pop()
  44.  
  45.     def handle_data(self, data):
  46.         for letter in data:
  47.             self.letters.append((letter, self.current_color[-1], self.current_font[-1], self.current_gimmick[-1]))
  48.  
  49.  
  50. def parse_text(text):
  51.     parser = AdvancedTextParser()
  52.     lines = []
  53.     for line in text.splitlines():
  54.         parser.feed(line)
  55.         lines.append(parser.letters)
  56.         parser.letters = []
  57.     print(lines)
  58.     return lines
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement