簡體   English   中英

Python:如何刪除以特定單詞開頭的句子

[英]Python: How to remove sentences starting with a specific word(s)

我正在嘗試刪除以某個短語開頭的整個句子,但我想保留正文的 rest。 例如:

text = "你好,我喜歡狗。我也喜歡貓。你好,我喜歡動物"

我想刪除任何以“Hello”開頭的句子,但保留 rest,因此 function 應該只留下:

“我也喜歡貓。”

目前我正在嘗試使用正則表達式,但我不確定實現這一點的方法。 任何幫助,將不勝感激。

這是一個基本的方法。 您可能需要使用更花哨的東西來拆分句子; 有關更多詳細信息,請參閱此帖子

>>> text = "Hello I like dogs. I also like cats. Hello I like animals"
>>> sentences = text.split(". ")
>>> ". ".join(s for s in sentences if not s.lower().startswith("hello")) + "."
'I also like cats.'

請閱讀代碼注釋:

text = "Hello I like dogs. I also like cats. Hello I like animals"
#get list of sentences, split by the DOT and space ". "
#like: ['Hello I like dogs', 'I also like cats', 'Hello I like animals']
t = text.split('. ')
#now lets loop for each value on our list
for v in t:
    #check if the first 5 letters are "Hello"
    if v[0:5] == 'Hello':
        #if it is - remove the value from the list.
        t.remove(v)
#now we have list of filtered strings:
#t

請注意,“Hello”這個詞可能是大寫/小寫,所以如果你想涵蓋所有內容,請在 if 處添加:

if v[0:5].casefold() == 'hello':

它將字符串稱為小寫。

暫無
暫無

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

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