Reputation: 411
I try to insert '#' in front of specific words in a sentence with an elegant solution (not a big function with many 'if').
hashwords = ['Google','Apple','Titan','Facebook']
input = 'Google,Apple, Titan and Facebook. Not Facebook@Work OpenTitan or apple.'
output = '#Google,#Apple, #Titan and #Facebook. Not Facebook@Work, OpenTitan or apple.'
I tried things like that, but I would like to take into account the punctuation or words that can be part of bigger words :
for elem in hashwords :
if elem in input:
input = input.replace(elem, '#'+elem)
Any idea?
Thanks
Upvotes: 0
Views: 2955
Reputation: 91518
import re
hashwords = ['Google','Apple','Titan','Facebook']
input = 'Google,Apple, Titan and Facebook. Not Facebook@Work OpenTitan or apple.'
for elem in hashwords :
input = re.sub(r'\b'+elem+r'\b(?!@)', '#'+elem, input)
print(input)
Output:
#Google,#Apple, #Titan and #Facebook. Not Facebook@Work OpenTitan or apple.
You can use r'(?<!@)\b'+elem+r'\b(?!@)'
if you don't want Apple@Titan
to be matched.
Upvotes: 4