I've done something like this, where the variable html is your code <html><body>word-one word-two word-one</body></html>
and I separated the text and the code then added them together.
soup = BeautifulSoup(html,'html.parser')
text = soup.text # Only the text from the soup
soup.body.clear() #Clear the text between the body tags
new_text = text.split() # Split beacuse of the spaces much easier
for i in new_text:
new_tag = soup.new_tag('span') #Create a new tag
new_tag.append(i) #Append i to it (from the list that's split between spaces)
#example new_tag('a') when we append 'word' to it it will look like <a>word</a>
soup.body.append(new_tag) #Append the whole tag e.g. <span>one-word</span)
We could also do this with Regular Expressions to match some word.
soup = BeautifulSoup(html, 'html.parser')
text = soup.text # Only the text from the soup
soup.body.clear() # Clear the text between the body tags
theword = re.search(r'\w+', text) # Match any word in text
begining, end = theword.start(), theword.end()
soup.body.append(text[:begining]) # We add the text before the match
new_tag = soup.new_tag('span') # Create a new tag
new_tag.append(text[begining:end])
# We add the word that we matched in between the new tag
soup.body.append(new_tag) # We append the whole text including the tag
soup.body.append(text[end:]) # Append everything that's left
I'm sure we could use .insert
in a similar manner.