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>
There is no replace() method in Dominate, but this solution works for what I want to achieve:
item = 'item1'
url = '/item1'
item_atag = '<a href={}>{}</a>'.format(url, item)
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)
html_with_atag = html_string.replace(item, item_atag)
with open('html_file.html', 'w') as f:
f.write(html_with_atag)