Convert Words in a Text to Custom HTML Links Automagically using Python

In this blog post, I'm going to show you how-to automate the conversion of words in a text to custom HTML links using Python. As content creators, we often encounter the need to transform specific words or keywords into affiliate links or clickable links that redirect readers to relevant web pages.

Convert Words in a Text to Custom HTML Links Automagically using Python
Photo by Kenny Eliason / Unsplash

In this blog post, I'm going to show you how-to automate the conversion of words in a text to custom HTML links using Python. As content creators, we often encounter the need to transform specific words or keywords into affiliate links or clickable links that redirect readers to relevant web pages. Manually editing each occurrence can be time-consuming and tedious, especially when dealing with large volumes of text. Well, no longer!

Here is the Python script with the text on line eight and the words to link starting on line 11:

def convert_specific_words_to_custom_links(text, word_links):
    for word, link in word_links.items():
        link_html = f'<a href="{link}">{word}</a>'
        text = text.replace(word, link_html)
    return text

# Example usage
text = "This is a sample text with specific words that should be converted into links."
word_links = {
    "blog": "https://example.com/blog",
    "affiliate": "https://example.com/affiliate"
}
html_text = convert_specific_words_to_custom_links(text, word_links)
print(html_text)

You can also use this slightly modified Python script that will search the text of a .txt file:

def convert_specific_words_to_custom_links(file_path, word_links):
    with open(file_path, 'r') as file:
        text = file.read()
        for word, link in word_links.items():
            link_html = f'<a href="{link}">{word}</a>'
            text = text.replace(word, link_html)
    return text

# Example usage
file_path = 'blogpost.txt'
word_links = {
    "blog": "https://example.com/blog",
    "affiliate": "https://example.com/words"
}
html_text = convert_specific_words_to_custom_links(file_path, word_links)
print(html_text)

In the second script, the text maybe found on line 10 in a .txt file called blogpost, and the words to link maybe found starting on line 12.