簡體   English   中英

從python列表中刪除字符串中所有出現的單詞

[英]Remove all occurrences of words in a string from a python list

我正在嘗試使用已編譯的正則表達式從字符串中匹配並刪除列表中的所有單詞,但是我正努力避免單詞中出現單詞。

當前:

 REMOVE_LIST = ["a", "an", "as", "at", ...]

 remove = '|'.join(REMOVE_LIST)
 regex = re.compile(r'('+remove+')', flags=re.IGNORECASE)
 out = regex.sub("", text)

在: “快速的棕色狐狸跳過了一只螞蟻”

出: “快速的棕色狐狸跳過了t”

預期: “快速的棕色狐狸跳過了”

我嘗試更改字符串以將其編譯為以下內容,但無濟於事:

 regex = re.compile(r'\b('+remove+')\b', flags=re.IGNORECASE)

有什么建議還是我遺漏了一些顯而易見的東西?

這是一個不使用正則表達式的建議,您可能要考慮:

>>> sentence = 'word1 word2 word3 word1 word2 word4'
>>> remove_list = ['word1', 'word2']
>>> word_list = sentence.split()
>>> ' '.join([i for i in word_list if i not in remove_list])
'word3 word4'

一個問題是只有第一個\\b位於原始字符串中。 第二個被解釋為退格字符(ASCII 8),而不是單詞邊界。

要修復,更改

regex = re.compile(r'\b('+remove+')\b', flags=re.IGNORECASE)

regex = re.compile(r'\b('+remove+r')\b', flags=re.IGNORECASE)
                                 ^ THIS

暫無
暫無

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

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