簡體   English   中英

刪除“ not”之后的第一個單詞

[英]Removing the first word after “ not”

我有一個字符串:

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

,我想刪除“ not”之后的第一個單詞。 我如何在python中實現它? 我正在尋找類似的結果:

"grocery store shop, sell milk"

要么

"grocery store, 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

如果要刪除直到下一個標點或行尾的字符,請嘗試以下操作:

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'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM