pythonhtmlreplacetext-filesdominate

Is there a function similar to .replace() in Dominate library for Python?


I want to add HTML tags to text taken from a .txt file and then save as HTML. I'm trying to find any instances of a particular word, then 'replace' it with the same word inside an anchor tag.

Something like this:

import dominate
from dominate.tags import *

item = 'item1'
text = ['here is item1 in a line of text', 'here is item2 in a line too']
doc = dominate.document()

with doc:
    for i, line in enumerate(text):
        if item in text[i]:
            text[i].replace(item, a(item, href='/item1')) 

The above code gives an error:

TypeError: replace() argument 2 must be str, not a.

I can make this happen:

print(doc.body)
<body>
  <p>here is item1 in a line of text</p>
  <p>here is item2 in a line too</p>
</body>

But I want this:

print(doc.body)
<body>
  <p>here is <a href='/item1'>item1</a> in a line of text</p>
  <p>here is item2 in a line too</p>
</body>

Solution

  • There is no replace() method in Dominate, but this solution works for what I want to achieve:

    1. Create the anchor tag as a string. Stored here in the variable 'item_atag':
        item = 'item1'
        url = '/item1'
        item_atag = '<a href={}>{}</a>'.format(url, item)
    
    1. Use Dominate library to wrap paragraph tags around each line in the original text, then convert to string:
        text = ['here is item1 in a line of text', 'here is item2 in a line too']
    
        from dominate import document
        from dominate.tags import p
    
        doc = document()
    
        with doc.body:
            for i, line in enumerate(text):
                p(text[i])
    
        html_string = str(doc.body)
    
    1. Use Python's built-in replace() method for strings to add the anchor tag:
        html_with_atag = html_string.replace(item, item_atag)
    
    1. Finally, write the new string to a HTML file:
        with open('html_file.html', 'w') as f:
            f.write(html_with_atag)