2017-06-29 50 views
-7

我想從字符串中移除單詞列表。python:如何從字符串中移除單詞

例如: 名單是:

["it's","didn't",isn't,"don't"] 

字符串爲:

'it's a toy,isn't a tool.i don't know anything.' 

我應該怎麼做刪除it'sdidn'tisn'tdon't從字符串?

+0

你能更具體一點嗎?字符串和列表如何相關? –

+1

你是說你想刪除列表中出現在字符串中的每一個單詞?你的措辭有點不清楚。 –

+0

@DavyM是的,英文是有點bad.sorry.any提示? – flystar

回答

0

有幾種方法可以做到這一點,我會解決2.一個是按字分割字符串,逐字比較要刪除單詞的字符串。另一種是掃描每個字符串的字符串。我將舉例說明每種方法的優缺點。

第一種方法是按字分割列表。這很好,因爲它可以覆蓋整個列表,並且可以使用列表理解來提取所需的值,但是,由於它只寫入空格,所以它會錯過任何觸及標點符號的內容。 This question解決了如何避免這個問題,以便這個答案可以工作。

your_string = "it's a toy,isn't a tool.i don't know anything." 
removal_list = ["it's","didn't","isn't","don't"] 

edit_string_as_list = your_string.split() 

final_list = [word for word in edit_string_as_list if word not in removal_list] 

final_string = ' '.join(final_list) 

第二個選項是按原樣刪除字符串中所有這些術語的所有實例。這很好,因爲它可以避免標點問題,但它有一個缺點;如果你刪除了某個東西而且它是另一個詞的一部分,那麼該部分將被刪除(例如,如果你有一個帶有「sand」字樣的字符串並嘗試刪除「and」,它將刪除「and」from「沙」,並留下‘S’字符串中。)

your_string = "it's a toy,isn't a tool.i don't know anything." 
removal_list = ["it's","didn't","isn't","don't"] 

for word in removal_list: 
    your_string = your_string.replace(word, "") 

我希望這些解決方案之一滿足您的需求。

0

試試這個:

s = "it's a toy,isn't a tool.i don't know anything." 
list = ["it's","didn't","isn't","don't"] 

split_line = s.split() 
for word in split_line: 
    if word in list: 
     list.remove(word) 
output = ' '.join(list) 

注意:這不佔地方的話是,如果他們要對抗的標點符號,像你這樣在這裏的不同情況實例:toy,isn't

+1

爲了說明那些標點符號的區別,[這個問題](https://stackoverflow.com/questions/1059559/split-strings-with-multiple-delimiters)解決了如何分割不僅僅是空白。 –

相關問題