I know that I can open multiple file using the with statement. My problem is that I can't catch errors separately. My function has a argument and an optional argument. If the "regular" is not given, it should throw an IOError, but if the optional argument (a file) is not given, then it should only return a warning message, and continue to run. So far I came up with this solution, my question is than is it possible to put these two file openining like this: with codecs.open(file, 'r', 'iso-8859-2') as f, codecs.open(stopfile, 'r', 'iso-8859-2') and check for errors separately?
import re
import codecs
def frequencyList(file, stopfile=''):
try:
with codecs.open(file, 'r', 'iso-8859-2') as f:
text = f.read()
frequentWords = []
if stopfile != '':
try:
with codecs.open(stopfile, 'r', 'iso-8859-2') as s:
for word in s:
frequentWords.append(word[:-2])
except:
pass
except IOError:
return 'File not found.'
text = re.sub(r'\W+', ' ', text).lower().split()
withoutFrequentWords = []
for word in text:
if word not in frequentWords:
withoutFrequentWords.append(word)
frequency = [withoutFrequentWords.count(word) for word in withoutFrequentWords]
dictionary = dict(zip(withoutFrequentWords, frequency))
result = [(dictionary[key], key) for key in dictionary]
result.sort()
result.reverse()
return result[:10]
if __name__ == '__main__':
print(frequencyList('1984.txt', 'stopwords.txt'))