如果打開了Python解釋器,你會發現,"doc" and "pdf" and "xls" and "jpg"
是同樣的事情'jpg'
:
>>> "doc" and "pdf" and "xls" and "jpg"
'jpg'
因此,而不是測試對所有的字符串,你的第一次嘗試只對'jpg'進行測試。
有很多方法可以做你想做的。下面的是不是最明顯的,但它是有用的:
if not any(test_string in text for test_string in ["doc", "pdf", "xls", "jpg"]):
filtered.append(text)
另一種方法是結合使用for
環路以else
聲明:
for test_string in ["doc", "pdf", "xls", "jpg"]:
if test_string in text:
break
else:
filtered.append(text)
最後,你可以使用純列表理解:
tofilter = ["one.pdf", "two.txt", "three.jpg", "four.png"]
test_strings = ["doc", "pdf", "xls", "jpg"]
filtered = [s for s in tofilter if not any(t in s for t in test_strings)]
編輯:
如果要篩選這兩個詞和擴展,我提出以下建議:
text_list = generate_text_list() # or whatever you do to get a text sequence
extensions = ['.doc', '.pdf', '.xls', '.jpg']
words = ['some', 'words', 'to', 'filter']
text_list = [text for text in text_list if not text.endswith(tuple(extensions))]
text_list = [text for text in text_list if not any(word in text for word in words)]
這可能仍然導致一些不匹配;上面還會過濾「做某事」,「他是個單詞」等。如果這是一個問題,那麼您可能需要更復雜的解決方案。
而不是編輯我會簡單地補充一點,如果你想忽略大小寫,你應該使用'str.lower()'方法 - 即text.lower()'中的''pdf'「。另外,使用'.endswith()'(S。Mark的回答)很好,因爲它不會拒絕像「mypdfprocessor.py」這樣的字符串。 – senderle 2011-02-27 17:47:30