Skip to main content
 首页 » 编程设计

python之删除不确定的子串

2025年05月04日14dflying

我对 python 比较陌生。假设我有以下字符串 -

tweet1= 'Check this out!! #ThrowbackTuesday I finally found this!!' 
tweet2= 'Man the summer is hot... #RisingSun #SummerIsHere Can't take it..' 

现在,我正在尝试删除推文中的所有 hashtags(#),这样 -

tweet1= 'Check this out!!  I finally found this!!' 
tweet2= 'Man the summer is hot...  Can't take it..' 

我的代码是 -

tweet1= 'Check this out!! #ThrowbackTuesday I finally found this!!' 
i,j=0,0 
s=tweet1 
while i < len(tweet1): 
    if tweet1[i]=='#': 
        j=i 
        while tweet1[j] != ' ': 
            ++j 
        while i<len(tweet1) and j<len(tweet1): 
            ++j 
            s[i]=tweet1[j] 
            ++i 
    ++i 
print(s) 

这段代码没有输出,也没有错误,这让我相信我使用了错误的逻辑。使用正则表达式有更简单的解决方案吗?

请您参考如下方法:

这是一个正则表达式解决方案:

re.sub(r'#\w+ ?', '', tweet1) 

正则表达式意味着删除一个哈希符号,后跟 1 个或多个单词字符(字母、数字或下划线),可选地后跟一个空格(这样您就不会连续得到两个空格)。

您可以通过 Google 在 Python 中找到很多关于正则表达式的一般信息,这并不难。

此外,要允许其他特殊字符,例如 $ 和 @,请将 \w 替换为 [\w$@ ],其中 $@ 可以替换为您喜欢的任何字符,即括号中的所有内容都是允许的。