在python字符串中插入主题标签

我试图用一种优雅的解决方案在句子中的特定单词前插入“#”(不是一个包含许多“ 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.'

我尝试过类似的操作,但我想考虑标点符号或可能属于较大单词的单词:

    for elem in hashwords :
        if elem in input:
            input = input.replace(elem,'#'+elem)

有什么主意吗?

谢谢

weipei_200811 回答:在python字符串中插入主题标签

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)

输出:

#Google,#Apple,#Titan and #Facebook. Not Facebook@Work OpenTitan or apple.

如果您不希望与r'(?<!@)\b'+elem+r'\b(?!@)'匹配,则可以使用Apple@Titan

本文链接:https://www.f2er.com/3150133.html

大家都在问