I have a class that needs a list of words to be excluded from a string:
class Cleaner():
def __init__(self, remove_words=None):
self.remove_words = remove_words
def clean(self, line):
return u' '.join[word for word in line not in self.remove_words]
and on the main file I need to read the words to be removed from the lines:
if __name__ == "__main__":
with open('remove_words') as r:
words = r.read().splitlines()
cleaning = Cleaner(words)
with open('mylines') as f:
lines = f.read()
for line in lines:
print cleaning.clean(line)
So I need to open the remove_words
file before creating the Clean
class. But alas, I need to open several files with words to be removed and the code get messy fast. So I added a class to set the removable words on the Clean
class:
class Cleaner():
def __init__(self, remove_words=None):
self.remove_words = remove_words
def set_remove_words(self, words):
self.remove_words = words
def clean(self, line):
return u' '.join[word for word in line not in self.remove_words]
so now the main code would look like
if __name__ == "__main__":
with open('remove_words') as r:
words = r.read().splitlines()
# after lots of these open files...
with open('remove_more_words') as r:
more_words = r.read().splitlines()
cleaning = Cleaner()
all_removable_words = words + more_worlds
cleaning.set_remove_words(all_removable_words)
with open('mylines') as f:
lines = f.read()
for line in lines:
print cleaning.clean(line)
but then again things can get very messy. There are cases when I will have to open and pass just one list of removable words, sometimes will be several. What would be a "pythonic" solution for this? Would move the filenames with removable words be passed to the constructor and build the lists there be more "pythonic" and less error prone? Where should the exceptions be handled?