所以,我有兩個文件,所以要檢查它的有效性,我執行try
和except
兩次。但我不認爲這是一個好方法,你能提出一個更好的方法嗎?如何執行兩個文件的錯誤處理?
這裏是我的代碼:
def form_density_dictionary(self,word_file,fp_exclude):
self.freq_dictionary={}
try:
with open(fp_exclude,'r')as fp2:
words_excluded=fp2.read().split() #words to be excluded stored in a list
print("**Read file successfully :" + fp_exclude + "**")
words_excluded=[words.lower() for words in words_excluded] # converted to lowercase
except IOError:
print("**Could not read file:", fp_exclude, " :Please check file name**")
sys.exit()
try:
with open(word_file,'r') as file:
print("**Read file successfully :" + word_file + "**")
words_list=file.read()
if not words_list:
print("**No data in file:",word_file +":**")
sys.exit()
words_list=words_list.split()
words_list=[words.lower() for words in words_list] # lowercasing entire list
unique_words=list((set(words_list)-set(words_excluded)))
self.freq_dictionary= {word:("%6.2f"%(float((words_list.count(word))/len(words_list))*100)) for word in unique_words}
#print((len(self.freq_dictionary)))
except IOError:
print("**Could not read file:", word_file, " :Please check file name**")
sys.exit()
任何其他建議也歡迎,使之更加符合Python。
還有兩個想法,使你的代碼更「Python化」:第一,使用'格式'而不是字符串concat'「**成功讀取文件:」+ fp_exclude +「**」 - >'「**成功讀取文件:{」**「.format(fp_exclude)'。其次,使用內置函數,如'map':'words_list = [words.lower()for words_list]' - >'list(map(str.lower,words))' –
是啊,謝謝mate :) –