[英]How can I remove all words that end in “:” from a string in Python?
[英]How to remove WHOLE words from a string in python?
我正在嘗試制作一個 function 來從 python 中的字符串中刪除整個單詞,我想我可以做到這一點:
def remove_words_from_str(strn, word, replacement=' '):
return re.sub(r'(\s*)'+word+'(\s*)', replacement, strn)
問題是這也需要一些單詞,這是我不想要的。
EX: print( remove_words_from_str( "is this is a test ? yes this is ; this is", "is" ) )
OUT: th a test ? yes th ; th
有沒有辦法只取整個單詞? (換句話說,我不希望 go 到 'th' 的 'this',因為 'this' 中的 'is' 不是一個完整的單詞)
Python 正則表達式支持\b
符號,表示“單詞”邊界。 所以你可以做
re.sub(r'\s*\b' + word + r'\b\s*', replacement, strn)
您仍然希望在兩側保留貪婪\s*
量詞,以用單個空格替換所有周圍的空格。
您的測試用例的 output 是
' this a test ? yes this ; this '
如果要確保刪除第一個和最后一個空格,請在結果上使用str.strip
:
def remove_words_from_str(strn, word, replacement=' '):
return re.sub(r'\s*\b' + word + r'\b\s*', replacement, strn).strip()
這對我有用。
def remove_words_from_str(strn, word, replacement=' '):
return re.sub(r'(^|\s+)'+word+'($|\s+)', replacement, strn)
您可以使用列表中的.split()
方法將其分解為單個單詞(如果沒有給出參數,則在空格處拆分)。 然后只需 go 與
list.remove(elem)
不使用正則表達式的解決方案:
def remove_words_from_str(strn, word, replacement=' '):
return " ".join([replacement if token==word else token for token in strn.split()])
這個怎么樣? 你的pattern
只是'is'
,所以你可以直接替換
s = 'is this is a test ? yes this is ; this is'
rm = 'is'
re.sub(rm , '', s)
Output: ' th a test? yes th; th '
' th a test? yes th; th '
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.