Regex在每个单词的开头插入一个字符

Regex在每个单词的开头插入一个字符,regex,python-3.x,Regex,Python 3.x,我在推特上搜索热门话题,目前有这样一个列表 Trending_Topics #facebookdown Lena Dunham #SaveThePlanetIn4Words #NationalPunctuationDay Lane Kiffin 现在,我想在字符串中的每个单词前面插入一个“+”号 但是,我当前的代码

我在推特上搜索热门话题,目前有这样一个列表

            Trending_Topics
             #facebookdown              
             Lena Dunham  
     #SaveThePlanetIn4Words   
     #NationalPunctuationDay     
             Lane Kiffin      
现在,我想在字符串中的每个单词前面插入一个“+”号

但是,我当前的代码

 df3['Keywords'] = df3.Trending_Topics.str.replace(r'(\b\S)', r'+\1')
将“+”放在标签字符串的#后面

 Trending_Topics
 #+facebookdown
 #+SavethePlanetIn4Words
 etc...
理想情况下,我的输出看起来也是如此

                Trending_Topics
             +#facebookdown              
             +Lena +Dunham  
     +#SaveThePlanetIn4Words   
     +#NationalPunctuationDay     
             +Lane +Kiffin  

有一个简单的正则表达式解决方案吗?

您需要使用一个否定的lookback断言

re.sub(r'(?<!\S)(\S)', r'+\1', st)
re.sub(r'(?)?

例如:

>>> import re
>>> s = '''             #facebookdown              
             Lena Dunham  
     #SaveThePlanetIn4Words   
     #NationalPunctuationDay     
             Lane Kiffin   '''
>>> print(re.sub(r'(?<!\S)(\S)', r'+\1', s))
             +#facebookdown              
             +Lena +Dunham  
     +#SaveThePlanetIn4Words   
     +#NationalPunctuationDay     
             +Lane +Kiffin   
>>重新导入
>>>s=''面朝下
莉娜·邓纳姆
#保存计划4个字
#国庆日
“基芬巷”
>>>打印(re.sub)(r’(?您可以使用:

import re
p = re.compile(ur'(?<=\s|^)(?=\S)', re.MULTILINE)

result = re.sub(p, u"+", input)
重新导入

p=re.compile(ur’(?使用您的代码得出:df3['Keywords']=df3.Trending_Topics.str.replace(r’(?)?
(?<=\s|^)  # assert if previous position is a space or line start
(?=\S)     # assert if next position is a non-space character