Program to enclose pattern into bold tag in Python?


Suppose we have a text and a list of strings called patterns, we have to define an embolden function where all substrings in text that match any string in the given patterns are wrapped in  and  tags. If any two patterns are adjacent or overlap, they should be merged into one tag.

So, if the input is like text = "thisissampleline" patterns = ["this", "issam", "sample"], then the output will be "a<b>bc</b>d<b>ef</b>g", as bc and ef match the text and are wrapped in <b> and </b> tags.

To solve this, we will follow these steps

  • n := size of text

  • bold := a list of size n, and fill with False values

  • for i in range 0 to n, do

    • for each p in patterns, do

      • if substring of text[from index i to end] is starts with p, then

        • for j in range 0 to size of p, do

          • bold[i + j] := True

  • ans := blank string

  • for i in range 0 to n, do

    • if bold[i] and (i is same as 0 or bold[i - 1] is false) , then

      • ans := ans concatente "<b>"

    • ans := ans + text[i]

    • if bold[i] and (i is same as n - 1 or bold[i + 1] is false) , then

      • ans := ans concatenate "</b>"

  • return ans

Let us see the following implementation to get better understanding

Example

 Live Demo

class Solution:
   def solve(self, text, patterns):
      n = len(text)
      bold = [False] * n
      for i in range(n):
         for p in patterns:
            if text[i:].startswith(p):
               for j in range(len(p)):
                  bold[i + j] = True

      ans = ""
      for i in range(n):
         if bold[i] and (i == 0 or not bold[i - 1]):
            ans += ""
          ans += text[i]
         if bold[i] and (i == n - 1 or not bold[i + 1]):
             ans += ""
      return ans

ob = Solution()
text = "thisissampleline"
patterns = ["this", "ssam", "sample"]
print(ob.solve(text, patterns))

Input

"thisissampleline", ["this", "ssam", "sample"]

Output

<b>this</b>i<b>ssample</b>line

Updated on: 10-Nov-2020

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements