zoukankan      html  css  js  c++  java
  • 面向对象例子

    
    class SearchEngineBase(object):
        def __init__(self):
            pass
    
        def add_corpus(self, file_path):
            with open(file_path, 'r') as fin:
                text = fin.read()
            self.process_corpus(file_path, text)
    
        def process_corpus(self, id, text):
            raise Exception('process_corpus not implemented.')
    
        def search(self, query):
            raise Exception('search not implemented.')
    
    def main(search_engine):
        for file_path in ['1.txt', '2.txt', '3.txt', '4.txt', '5.txt']:
    	    ##遍历文件,将文件的内容放到字典,健 为文件名,值为内容
            search_engine.add_corpus(file_path)
    
        while True:
            query = input()
            results = search_engine.search(query)
            print('found {} result(s):'.format(len(results)))
            for result in results:
                print(result)
    
    
    
    
    
    
    
    
    
    
    class SimpleEngine(SearchEngineBase):
        def __init__(self):
    	    ##调用父类的构造函数
            super(SimpleEngine, self).__init__()
            self.__id_to_texts = {}
    
        def process_corpus(self, id, text):
    	     ##键值为文件名,内容为值
            self.__id_to_texts[id] = text
    
        def search(self, query):
            results = []
    		##搜索的词出现在字典的值中 返回内容
            for id, text in self.__id_to_texts.items():
                if query in text:
                    results.append(id)
            return results
    
    search_engine = SimpleEngine()
    main(search_engine)
    
    
    ########## 输出 ##########
    
    
    simple
    found 0 result(s):
    little
    found 2 result(s):
    1.txt
    2.txt
  • 相关阅读:
    DS博客作业02--栈和队列
    DS博客作业02--线性表
    c博客06-结构
    c博客作业05--指针
    C博客作业04--数组
    博客作业03-函数
    循环结构
    c博客作业01--分支、顺序结构
    我的第一篇博客
    Macos安装JDK1.8
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13348368.html
Copyright © 2011-2022 走看看