"移除「不」之後的第一個單詞"

2024-04-27 04:23:09 发布

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

我有一个字符串:

s = "grocery store not liquor shop not restaurant, sell milk"

,我想去掉“不是”后面的第一个字。如何在python中实现它?我在寻找这样的结果:

"grocery store shop, sell milk"

或者

"grocery store, sell milk"

如果删除“not”和任何标点/字符串结尾之间的所有单词也是可能的。你知道吗


Tags: store字符串结尾notshop单词restaurantmilk
3条回答

如果要删除到下一个标点或行尾的字符,请尝试以下操作:

s = "grocery store not liquor shop not restaurant, sell milk"
re.sub(r'\b\s*not\s+[\w\s]+', '', s)

结果

'grocery store, sell milk'

基本上,删除所有以“not”开头的字符串,后跟空格,后跟所有可用的非(单词或空格)字符,即标点符号。如果您也想去掉尾随逗号,请尝试以下修改:

s = "grocery store not liquor shop not restaurant, sell milk"
re.sub(r'\b\s*not\s+[\w\s]+[^\w\s]?', '', s)

尾随的?确保行的结尾与实际的点蚀匹配。你知道吗

这些表达式适用于极端情况,如

not milk

如果你不想用re,你可以用循环。你知道吗

def remove_after(string, kwrd):
    s = string.split(' ')
    new = []
    skip = []
    for i,v in enumerate(s):
        if v != kwrd:
            if i not in skip:
                new.append(v)
        else:
            skip.append(i+1)
    return ' '.join(new)

print(remove_after("grocery store not liquor shop not restaurant, sell milk", 'not'))

你可以这样做:

import re
s = "grocery store not liquor shop not restaurant, sell milk"

print (re.sub(r'\s+not \w+', '', s))

你会得到这个:

grocery store shop, sell milk

相关问题 更多 >