Skip to main content
 首页 » 编程设计

python之读取一些文件并通过 setter 传递给构造函数

2024年10月24日12findumars

我有一个类需要从字符串中排除的单词列表:

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] 

在主文件中,我需要读取要从行中删除的单词:

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) 

所以我需要在创建Clean 类之前打开remove_words 文件。但是,唉,我需要打开几个文件,其中包含要删除的单词,代码很快就会变得困惑。所以我添加了一个类来设置 Clean 类上的可移动单词:

 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] 

所以现在主要代码看起来像

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) 

但话又说回来,事情会变得非常困惑。在某些情况下,我将不得不打开并传递一个可移动单词列表,有时会是几个。什么是“pythonic”解决方案?将带有可移动单词的文件名传递给构造函数并构建列表,使其更“pythonic”且更不容易出错?应该在哪里处理异常?

请您参考如下方法:

首先,做好将文件 I/O 置于类之外的工作。我喜欢您如何遵守 Bob 叔叔的干净架构原则。您绝对不应该将它移到构造函数中,因为这会将您的域规则代码耦合到 open 函数,从而降低它的可重用性。

我会利用列表理解和生成器来实现 Pythonic。

if __name__ == "__main__": 
 
     bad_word_sources = ['remove_words',...,'remove_more_words'] 
     bad_word_files = (open(source) for source in bad_word_sources)        
     bad_words = [word for word in chain(bad_word_files)] 
 
     cleaning = Cleaner(bad_words) 

这是有效的,因为 open() 函数提供了一个 __iter__ 实现,其工作方式类似于

[line for line in file.readlines()] 

当 open 对象耗尽时,它将自行关闭[需要引用]。

我不确定你想处理哪种异常,你能更具体一点吗?

另请注意,set_words 方法被视为 unpythonic .如果需要,只需直接设置属性即可。


旁注这个类only has 2 methods, one of which is __init__ :

 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] 

使这个可重用的 Pythonic 方法是抛弃类并将其放入模块中:

cleaner.py

def clean(line, bad_words): 
    return u' '.join(word for word in line if line not in self.bad_words) 

然后您可以像这样使用它:

from cleaner import clean 

代替:

from cleaner import Cleaner 
mycleaner = Cleaner(bad_words) 
mycleaner.clean(line) 

这真是令人困惑。