簡體   English   中英

如何從字符串中刪除特定的單詞?

[英]How to strip a specific word from a string?

我需要從字符串中刪除特定的單詞。

但我發現 python strip 方法似乎無法識別有序單詞。 只是剝離傳遞給參數的任何字符。

例如:

>>> papa = "papa is a good man"
>>> app = "app is important"
>>> papa.lstrip('papa')
" is a good man"
>>> app.lstrip('papa')
" is important"

我怎樣才能用 python 去除指定的單詞?

使用str.replace

>>> papa.replace('papa', '')
' is a good man'
>>> app.replace('papa', '')
'app is important'

或者使用re並使用正則表達式。 這將允許刪除前導/尾隨空格。

>>> import re
>>> papa = 'papa is a good man'
>>> app = 'app is important'
>>> papa3 = 'papa is a papa, and papa'
>>>
>>> patt = re.compile('(\s*)papa(\s*)')
>>> patt.sub('\\1mama\\2', papa)
'mama is a good man'
>>> patt.sub('\\1mama\\2', papa3)
'mama is a mama, and mama'
>>> patt.sub('', papa3)
'is a, and'

最簡單的方法是簡單地用空字符串替換它。

s = s.replace('papa', '')

您還可以在re.sub使用正則表達式:

article_title_str = re.sub(r'(\s?-?\|?\s?Times of India|\s?-?\|?\s?the Times of India|\s?-?\|?\s+?Gadgets No'',
                           article_title_str, flags=re.IGNORECASE)

如果您知道字符數組中要替換的每個單詞的開頭和結尾的索引值,並且您只想替換該特定數據塊,則可以這樣做。

>>> s = "papa is papa is papa"
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(s)
papa is mama is papa

或者,如果您還希望保留原始數據結構,則可以將其存儲在字典中。

>>> bin = {}
>>> s = "papa is papa is papa"
>>> bin["0"] = s
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(bin["0"])
papa is papa is papa
>>> print(s)
papa is mama is papa

一個有點“懶惰”的方法是使用startswith - 它更容易理解,而不是正則表達式。 但是正則表達式可能工作得更快,我還沒有測量。

>>> papa = "papa is a good man"
>>> app = "app is important"
>>> strip_word = 'papa'
>>> papa[len(strip_word):] if papa.startswith(strip_word) else papa
' is a good man'
>>> app[len(strip_word):] if app.startswith(strip_word) else app
'app is important'

如果只想從string 的開頭刪除單詞,則可以執行以下操作:

  string[string.startswith(prefix) and len(prefix):]  

其中 string 是您的字符串變量,而 prefix 是您要從字符串變量中刪除的前綴。

例如:

  >>> papa = "papa is a good man. papa is the best."  
  >>> prefix = 'papa'
  >>> papa[papa.startswith(prefix) and len(prefix):]
  ' is a good man. papa is the best.'

核實:

use replace()
------------
var.replace("word for replace"," ")
-----------------------------------
one = " papa is a good man"

two = " app is important"

one.replace(" papa ", " ")

output=> " is a good man"

two.replace(" app ", " ")

output=> " is important

如果我們談論的是前綴和后綴,並且您的 Python 版本至少為 3.9,那么您可以使用這些新方法

>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'

>>> 'MiscTests'.removesuffix('Tests')
'Misc'
>>> 'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'

最好是

  1. 拆分的話

  2. 用if語句加入我們感興趣的(你可以傳入多個單詞來剝離)

    sentence = "爸爸是個好人"

    ' '.join(句子中的單詞。split()如果單詞不在 ['papa'] 中)

暫無
暫無

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

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