在python字符串中插入hashtags

2024-09-19 22:34:46 发布

您现在位置: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)

你知道吗?你知道吗

谢谢


Tags: orandappleinputfacebookifgooglenot
1条回答
网友
1楼 · 发布于 2024-09-19 22:34:46
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.

如果不希望Apple@Titan匹配,可以使用r'(?<!@)\b'+elem+r'\b(?!@)'。你知道吗

相关问题 更多 >