我是新來的Python,並與來自StackOverflow的一些真正偉大的援助,我寫了一個程序:如何構建Python函數以便在錯誤後繼續執行?
1)看起來在一個給定的目錄,並在該目錄中的每個文件:
2 )運行一個HTML的清洗程序,其中:
- 打開帶有BeautifulSoup每個文件
- 黑名單中刪除標籤&內容
- Prettifies剩餘CONT耳鼻喉科
- 運行漂白劑去除所有非白名單標籤&屬性
- 保存作爲一個新的文件
它工作得很好,當它擊中某樣文件內容拋出了一堆除BeautifulSoup錯誤並終止整個事情。我希望它能夠很強大,因爲我無法控制這個目錄中的內容。
因此,我的問題是:如何重新構造程序,以便當它在目錄中的一個文件上發生錯誤時報告它無法處理該文件,然後繼續運行剩餘的文件?
這裏是我到目前爲止的代碼(與外來細節刪除):
def clean_dir(directory):
os.chdir(directory)
for filename in os.listdir(directory):
clean_file(filename)
def clean_file(filename):
tag_black_list = ['iframe', 'script']
tag_white_list = ['p', 'div']
attr_white_list = {'*': ['title']}
with open(filename, 'r') as fhandle:
text = BeautifulSoup(fhandle)
text.encode("utf-8")
print "Opened "+ filename
# Step one, with BeautifulSoup: Remove tags in tag_black_list, destroy contents.
[s.decompose() for s in text(tag_black_list)]
pretty = (text.prettify())
print "Prettified"
# Step two, with Bleach: Remove tags and attributes not in whitelists, leave tag contents.
cleaned = bleach.clean(pretty, strip="TRUE", attributes=attr_white_list, tags=tag_white_list)
fout = open("../posts-cleaned/"+filename, "w")
fout.write(cleaned.encode("utf-8"))
fout.close()
print "Saved " + filename +" in /posts-cleaned"
print "Done"
clean_dir("../posts/")
我尋找如何寫這個,使其繼續運行任何指導創下了解析/編碼/內容後/ clean_file函數中的屬性/ etc錯誤。
捕獲BS引發的異常。 – 2012-10-23 13:18:10
看看http://docs.python.org/tutorial/errors.html#user-defined-exceptions 「嘗試」和「除了」是你的朋友:) – cb0