2012-02-22 27 views
2

我試圖從字符串中刪除單詞(如果它們與列表匹配)。如果它與列表中的項目匹配,則替換字符串中的項目

x = "How I Met Your Mother 7x17 (HDTV-LOL) [VTV] - Mon, 20 Feb 2012" 

tags = ['HDTV', 'LOL', 'VTV', 'x264', 'DIMENSION', 'XviD', '720P', 'IMMERSE'] 

print x 

for tag in tags: 
    if tag in x: 
     print x.replace(tag, '') 

它產生這樣的輸出:

How I Met Your Mother 7x17 (HDTV-LOL) [VTV] - Mon, 20 Feb 2012 
How I Met Your Mother 7x17 (-LOL) [VTV] - Mon, 20 Feb 2012 
How I Met Your Mother 7x17 (HDTV-) [VTV] - Mon, 20 Feb 2012 
How I Met Your Mother 7x17 (HDTV-LOL) [] - Mon, 20 Feb 2012 

我希望它刪除匹配列表中的所有的話。

+11

LOL盜版過濾器愛它。 – 2012-02-22 14:04:01

回答

11

您並不保留x.replace()的結果。請嘗試使用以下代碼:

for tag in tags: 
    x = x.replace(tag, '') 
print x 

請注意,您的方法可以匹配任何子字符串,而不僅僅是完整的單詞。例如,它將刪除RUN LOLA RUN中的LOL

解決此問題的一種方法是將每個標記包含在一對r'\b'字符串中,然後查找生成的regular expression。該r'\b'將只匹配在單詞邊界:

for tag in tags: 
    x = re.sub(r'\b' + tag + r'\b', '', x) 
+0

謝謝!任何方式刪除括號「[],()」?當我將它們添加到列表中時,我得到無效的表達式錯誤。 – koogee 2012-02-22 15:40:53

+0

@ koogee:我推薦使用原始的非正則表達式來處理特殊字符('[',']','(',')'等等)。 – NPE 2012-02-22 15:42:05

+0

將'['']'添加到列表中給出'File'test3.py「,第23行,在 x = re.sub(r'\ b'+ tag + r'\ b','',x ) 文件「/usr/lib64/python2.7/re.py」,行151,在sub return _compile(pattern,flags).sub(repl,string,count) 文件「/ usr/lib64/python2。 7/re.py「,第244行,在_compile 引發錯誤,v#無效表達式 sre_constants.error:意外結束的正則表達式' – koogee 2012-02-22 16:18:18

5

str.replace()不到位改變字符串的方法 - 字符串在Python是不可改變的。你必須綁定xreplace()在每次迭代中返回的新字符串:

for tag in tags: 
    x = x.replace(tag, "") 

注意,if語句是多餘的;如果找不到匹配項,str.replace()將不會執行任何操作。

+2

+1:'如果'是完全redudant(雙重搜索) – juliomalegria 2012-02-22 14:08:51

1

(1)x.replace(tag, '')不修改x,而是返回一個字符串替換。

(2)你爲什麼要在每次迭代中打印?

你可以做最簡單的修改是:

for tag in tags: 
    x = x.replace(tag, '') 
3

使用的變量tagsx,您可以使用此:

output = reduce(lambda a,b: a.replace(b, ''), tags, x) 

回報:

'How I Met Your Mother 7x17 (-) [] - Mon, 20 Feb 2012' 
相關問題