我试着在句子中的特定单词前面插入“#”,并给出一个优雅的解决方案(不是一个包含许多“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)
你知道吗?你知道吗
谢谢
输出:
如果不希望
Apple@Titan
匹配,可以使用r'(?<!@)\b'+elem+r'\b(?!@)'
。你知道吗相关问题 更多 >
编程相关推荐