0

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'))

1 Answers1

0

I would say that since you wish to allow there not being a stopfile your code would actually get messier trying to open two files one of which may not exist and one of which must than it currently is because you would have to check which file produced the error and suppress the exception if it was the stopfile.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
  • I see. But isn't there some cleaner code for this? Mine looks a little messy. –  Jan 19 '14 at 10:58