删除不定子字符串

2024-05-20 14:37:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

现在,我正在尝试删除tweets中的所有标签(#),以便-

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)

这段代码没有给我任何输出和错误,这使我相信我使用了错误的逻辑。使用regex有更简单的解决方案吗?你知道吗


Tags: thelenischeckoutthissummerhot
3条回答

你可以利用^{}^{}来完成你的任务。你知道吗

这里split将使您的tweet字符串成为由空格分隔的单词列表。因此,在创建一个新列表时,只要使用startswith省略以#开头的任何内容。然后' '.join将使它再次成为一个由空格分隔的字符串。你知道吗

代码可以写成

tweet = 'Check this out!! #ThrowbackTuesday I finally found this!!'
print(' '.join([w for w in tweet.split() if not w.startswith('#')]))

输出:

Check this out!! I finally found this!!

Python没有++操作符,所以++j只对+操作符应用j两次,当然,这什么也不做。你应该改用j += 1。你知道吗

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

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

regex意味着删除一个哈希符号,后跟一个或多个单词字符(字母、数字或下划线),可以选择后跟一个空格(这样一行中就不会有两个空格)。你知道吗

一般来说,你可以找到大量关于regex的信息,用Python和Google,这并不难。你知道吗

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

相关问题 更多 >