예제 #1
0
class WudaoCommand:
    def __init__(self):
        # Member
        self.word = ''
        self.param_list = []
        self.draw_conf = True
        self.is_zh = False
        # Init
        self.param_separate()
        self.painter = CommandDraw()
        self.history_manager = UserHistory()
        # client
        self.client = WudaoClient()

    # init parameters
    def param_separate(self):
        if len(sys.argv) == 1:
            self.param_list.append('h')
        else:
            for v in sys.argv[1:]:
                if v.startswith('-'):
                    self.param_list.append(v[1:])
                else:
                    self.word += ' ' + v
        self.word = self.word.strip()
        if self.word:
            if not is_alphabet(self.word[0]):
                self.is_zh = True

    # process parameters
    def param_parse(self):
        if len(self.param_list) == 0:
            return
        if 'h' in self.param_list or '-help' in self.param_list:
            print('Usage: wd [OPTION]... [WORD]')
            print('Youdao is wudao, An powerful dict.')
            print('-k, --kill                   kill the server process')
            print('-h, --help                   display this help and exit')
            print(
                '-s, --short-desc             show description without the sentence'
            )
            print('-o, --online-search          search word online')
            exit(0)
        # close server
        if 'k' in self.param_list or '-kill' in self.param_list:
            self.client.close()
            sys.exit(0)
        # short conf
        if 's' in self.param_list or '-short-desc' in self.param_list:
            self.draw_conf = False
        if not self.word:
            print('Usage: wdd [OPTION]... [WORD]')
            exit(0)

    # query word
    def query(self):
        # query on server
        server_context = self.client.get_word_info(self.word).strip()
        if server_context != 'None':
            wi = json.loads(server_context)
            if self.is_zh:
                self.painter.draw_zh_text(wi, self.draw_conf)
            else:
                self.history_manager.add_item(self.word)
                self.painter.draw_text(wi, self.draw_conf)
        else:
            # Online search
            if 'o' in self.param_list or '-online-search' in self.param_list:
                try:
                    from src.WudaoOnline import get_text, get_zh_text
                    from urllib.error import URLError
                    if self.is_zh:
                        word_info = get_zh_text(self.word)
                    else:
                        word_info = get_text(self.word)
                    if not word_info['paraphrase']:
                        print('No such word: %s found online' % self.word)
                        exit(0)
                    self.history_manager.add_item(self.word)
                    if not self.is_zh:
                        self.history_manager.add_word_info(word_info)
                        self.painter.draw_text(word_info, self.draw_conf)
                    else:
                        self.painter.draw_zh_text(word_info, self.draw_conf)
                except ImportError:
                    print('You need install bs4 first.')
                    print('Use \'pip3 install bs4\' or get bs4 online.')
                except URLError:
                    print('No Internet : Please check your connection first')
            else:
                # search in online cache first
                word_info = self.history_manager.get_word_info(self.word)
                if word_info:
                    self.history_manager.add_item(self.word)
                    self.painter.draw_text(word_info, self.draw_conf)
                else:
                    print('Error: no such word :' + self.word)
                    print('You can use -o to search online.')
예제 #2
0
class WudaoCommand:
    def __init__(self):
        # Member
        self.word = ''
        self.param_list = []
        self.conf = {"short": False, "save": False}
        self.is_zh = False
        # Init
        self.param_separate()
        self.painter = CommandDraw()
        self.history_manager = UserHistory()
        # client
        self.client = WudaoClient()

    # init parameters
    def param_separate(self):
        if len(sys.argv) == 1:
            self.param_list.append('h')
        else:
            for v in sys.argv[1:]:
                if v.startswith('-'):
                    self.param_list.append(v[1:])
                else:
                    self.word += ' ' + v
        self.word = self.word.strip()
        if self.word:
            if not is_alphabet(self.word[0]):
                self.is_zh = True

    # process parameters
    def param_parse(self):
        if len(self.param_list) == 0:
            return
        if 'h' in self.param_list or '-help' in self.param_list:
            print('Usage: wd [OPTION]... [WORD]')
            print('Youdao is wudao, a powerful dict.')

            print('-k, --kill             kill the server process    (退出服务进程)')
            print('-h, --help             display this help and exit (查看帮助)')
            print('-s, --short-desc       do not show sentence       (只看释义)')
            print('-n, --not-save         query and save to notebook (不存入生词本)')
            print('生词本文件: ' + os.path.abspath('./usr/') + '/notebook.txt')
            print('查询次数: ' + os.path.abspath('./usr/') + '/usr_word.json')
            #print('-o, --online-search          search word online')
            exit(0)
        # close server
        if 'k' in self.param_list or '-kill' in self.param_list:
            self.client.close()
            sys.exit(0)
        # short conf
        if 's' in self.param_list or '-short-desc' in self.param_list:
            self.conf['short'] = True
        if 'n' in self.param_list or '-not-save' in self.param_list:
            self.conf['save'] = True
        if not self.word:
            print('Usage: wd [OPTION]... [WORD]')
            exit(0)

    # query word
    def query(self):
        word_info = {}
        # query on server
        server_context = self.client.get_word_info(self.word).strip()
        if not self.is_zh:
            self.history_manager.add_item(self.word)
        if server_context != 'None':
            word_info = json.loads(server_context)
            if self.is_zh:
                self.painter.draw_zh_text(word_info, self.conf)
            else:

                self.painter.draw_text(word_info, self.conf)
        else:
            # search in online cache first
            word_info = self.history_manager.get_word_info(self.word)
            if word_info:
                self.painter.draw_text(word_info, self.conf)
            else:
                if ie():
                    init()
                    try:
                        # online search
                        from src.WudaoOnline import get_text, get_zh_text
                        from urllib.error import URLError
                        import bs4
                        import lxml
                        if self.is_zh:
                            word_info = get_zh_text(self.word)
                        else:
                            word_info = get_text(self.word)
                        if not word_info['paraphrase']:
                            print('No such word: %s found online' %
                                  (self.painter.RED_PATTERN % self.word))
                            exit(0)
                        # store struct
                        self.history_manager.add_word_info(word_info)
                        if not self.is_zh:
                            self.painter.draw_text(word_info, self.conf)
                        else:
                            self.painter.draw_zh_text(word_info, self.conf)
                    except ImportError:
                        print('Word not found, auto Online search...')
                        print('You need install bs4, lxml first.')
                        print('Use ' + self.painter.RED_PATTERN %
                              'sudo pip3 install bs4 lxml' +
                              ' or get bs4 online.')
                        exit(0)
                    except URLError:
                        print('Word not found, auto Online search...')
                        print('No Internet : connection time out.')
                else:
                    print('Word not found, auto Online search...')
                    print(
                        'No Internet : Please check your connection or try again.'
                    )
                    exit(0)
        if not self.conf['save'] and not self.is_zh:
            self.history_manager.save_note(word_info)
예제 #3
0
class WudaoCommand:
    def __init__(self):
        # Member
        self.UserConfig = UserConfig()
        self.word = ''
        self.param_list = []
        self.conf = {"short": False, "save": False}
        self.is_zh = False
        # Init
        self.param_separate()
        self.painter = CommandDraw()
        self.history_manager = UserHistory()
        # client
        self.client = WudaoClient()
        # server
        self.server = WudaoServer(1, 'WudaoServer')
        self.server.start()

    # init parameters
    def param_separate(self):
        if len(sys.argv) == 1:
            self.param_list.append('h')
        else:
            for v in sys.argv[1:]:
                if v.startswith('-'):
                    self.param_list.append(v[1:])
                else:
                    self.word += ' ' + v
        self.word = self.word.strip()
        if self.word:
            if not is_alphabet(self.word[0]):
                self.is_zh = True

    # process parameters
    def param_parse(self):
        if len(self.param_list) == 0:
            return
        if 'h' in self.param_list or '-help' in self.param_list:
            print('Usage: wd [OPTION]... [WORD]')
            print('Youdao is wudao, a powerful dict.')
            print('-h, --help             display this help and exit         (查看帮助)')
            print('-S, --short-desc       show sentence or not               (只看释义)')
            print('-s  --save             save currently querying word       (保存当前正在查询的词)')
            print('-a, --auto-save        auto save to notebook or not       (是否自动存入生词本)')
            print('-n  --notebook         show notebook                      (输出生词本内容)')
            print('-d  --delete           delete word from notebook          (从单词本中删除指定单词)')
            print('-w  --word-count       show word count                    (输出查词计数)')
            print('-c  --config           show config                        (查看当前配置)')
            exit(0)

        # switch short desc
        if 'S' in self.param_list or '-short-desc' in self.param_list:
            if self.conf['short']:
                self.conf['short'] = False
                print('简略输出: 关')
            else:
                self.conf['short'] = True
                print('简略输出: 开')
            self.UserConfig.conf_dump(self.conf)
            exit(0)

        # switch auto save
        if 'a' in self.param_list or '-auto-save' in self.param_list:
            if self.conf['save']:
                self.conf['save'] = False
                print('自动保存到生词本: 关')
            else:
                self.conf['save'] = True
                print('自动保存到生词本: 开')
            self.UserConfig.conf_dump(self.conf)
            exit(0)

        # save currently word
        if 's' in self.param_list or '-save' in self.param_list:
            if self.is_zh:
                print('生词本只能保存英文单词')
                exit(2)
            self.query_without_print()
            if not self.conf['save']:  # 若默认自动保存生词,则不必重复保存
                self.history_manager.save_note(self.word, self.word_info)
            self.paint()
            print(self.word + ' 已被存入生词本')
            exit(0)

        # print notebook
        if 'n' in self.param_list or '-notebook' in self.param_list:
            try:
                note = self.history_manager.get_note()
            except notebookIsEmpty:
                print('生词本为空!')
                exit(3)
            for i in note:
                self.painter.draw_text(note[i], self.conf)
            exit(0)

        # delete word from notebook
        if 'd' in self.param_list or '-delete' in self.param_list:
            if self.word == '':
                print('请输入要删除的单词!')
                exit(4)
            self.query_without_print()
            try:
                self.history_manager.del_note(self.word)
            except notebookIsEmpty:
                print('生词本为空!')
                exit(3)
            print(self.word, '已从生词本中删除')
            exit(0)

        # print word count
        if 'w' in self.param_list or '-wordcount' in self.param_list:
            word_count = self.history_manager.get_word_count()
            print('您的查词次数为')
            for key, value in word_count.items():
                print(key + '\t' + str(value) + '次')
            exit(0)

        # status
        if 'c' in self.param_list or '-status' in self.param_list:
            self.conf = self.UserConfig.conf_read()
            if self.conf['short']:
                print('简略输出: 开')
            else:
                print('简略输出: 关')
            if self.conf['save']:
                print('自动保存到生词本: 开')
            else:
                print('自动保存到生词本: 关')
            exit(0)

        if not self.word:
            exit(0)

    # query word
    def query_without_print(self):
        self.word_info = {}
        server_contex = self.client.get_word_info(self.word).strip()
        if server_contex != 'None':
            self.word_info = json.loads(server_contex)
        else:
            self.word_info = self.history_manager.get_word_info(self.word)
            if not self.word_info:
                if ie():
                    try:
                        from src.WudaoOnline import get_text, get_zh_text
                        from urllib.error import URLError
                        import bs4
                        import lxml
                        self.word_info = get_text(self.word)
                        if not self.word_info['paraphrase']:
                            print('No such word: %s found online' % (self.painter.RED_PATTERN % self.word))
                            exit(0)
                        self.history_manager.add_word_info(self.word_info)
                    except ImportError:
                        print('Word not found, auto Online search...')
                        print('You need install bs4, lxml first.')
                        print('Use ' + self.painter.RED_PATTERN % 'sudo pip3 install bs4 lxml' + ' or get bs4 online.')
                        exit(0)
                    except URLError:
                        print('Word not found, auto Online search...')
                        print('No Internet : connection time out.')
                else:
                    print('Word not found, auto Online search...')
                    print('No Internet : Please check your connection or try again.')
                    exit(0)

    def paint(self):
        self.query_without_print()
        if self.is_zh:
            self.painter.draw_zh_text(self.word_info, self.conf)
        else:
            self.painter.draw_text(self.word_info, self.conf)
        if self.conf["save"] and not self.is_zh:
            self.history_manager.save_note(self.word, self.word_info)
        return
예제 #4
0
class WudaoCommand:
    def __init__(self):
        # Member
        self.word = ''
        self.param_list = []
        self.conf = {"short": False, "save": False}
        self.is_zh = False
        # Init
        self.param_separate()
        self.painter = CommandDraw()
        self.history_manager = UserHistory()
        # client
        self.client = WudaoClient()

    # init parameters
    def param_separate(self):
        if len(sys.argv) == 1:
            self.param_list.append('h')
        else:
            for v in sys.argv[1:]:
                if v.startswith('-'):
                    self.param_list.append(v[1:])
                else:
                    self.word += ' ' + v
        self.word = self.word.strip()
        if self.word:
            if not is_alphabet(self.word[0]):
                self.is_zh = True

    # process parameters
    def param_parse(self):
        if len(self.param_list) == 0:
            return
        if 'h' in self.param_list or '-help' in self.param_list:
            print('Usage: wd [OPTION]... [WORD]')
            print('Youdao is wudao, a powerful dict.')
            
            print('-k, --kill             kill the server process    (退出服务进程)')
            print('-h, --help             display this help and exit (查看帮助)')
            print('-s, --short-desc       do not show sentence       (只看释义)')
            print('-n, --not-save         query and save to notebook (不存入生词本)')
            print('生词本文件: ' + os.path.abspath('./usr/') + '/notebook.txt')
            print('查询次数: ' + os.path.abspath('./usr/') + '/usr_word.json')
            #print('-o, --online-search          search word online')
            exit(0)
        # close server
        if 'k' in self.param_list or '-kill' in self.param_list:
            self.client.close()
            sys.exit(0)
        # short conf
        if 's' in self.param_list or '-short-desc' in self.param_list:
            self.conf['short'] = True
        if 'n' in self.param_list or '-not-save' in self.param_list:
            self.conf['save'] = True
        if not self.word:
            print('Usage: wd [OPTION]... [WORD]')
            exit(0)

    # query word
    def query(self):
        word_info = {}
        # query on server
        server_context = self.client.get_word_info(self.word).strip()
        if not self.is_zh:
            self.history_manager.add_item(self.word)
        if server_context != 'None':
            word_info = json.loads(server_context)
            if self.is_zh:
                self.painter.draw_zh_text(word_info, self.conf)
            else:
                
                self.painter.draw_text(word_info, self.conf)
        else:
            # search in online cache first
            word_info = self.history_manager.get_word_info(self.word)
            if word_info:
                self.painter.draw_text(word_info, self.conf)
            else:
                if ie():
                    try:
                        # online search
                        from src.WudaoOnline import get_text, get_zh_text
                        from urllib.error import URLError
                        import bs4
                        import lxml
                        if self.is_zh:
                            word_info = get_zh_text(self.word)
                        else:
                            word_info = get_text(self.word)
                        if not word_info['paraphrase']:
                            print('No such word: %s found online' % (self.painter.RED_PATTERN % self.word))
                            exit(0)
                        # store struct
                        self.history_manager.add_word_info(word_info)
                        if not self.is_zh:
                            self.painter.draw_text(word_info, self.conf)
                        else:
                            self.painter.draw_zh_text(word_info, self.conf)
                    except ImportError:
                        print('Word not found, auto Online search...')
                        print('You need install bs4, lxml first.')
                        print('Use ' + self.painter.RED_PATTERN % 'sudo pip3 install bs4 lxml' + ' or get bs4 online.')
                        exit(0)
                    except URLError:
                        print('Word not found, auto Online search...')
                        print('No Internet : connection time out.')
                else:
                    print('Word not found, auto Online search...')
                    print('No Internet : Please check your connection or try again.')
                    exit(0)
        if not self.conf['save'] and not self.is_zh:
            self.history_manager.save_note(word_info)
예제 #5
0
class WudaoCommand:
    def __init__(self):
        # Member
        self.word = ''
        self.param_list = []
        # Init
        self.param_separate()
        self.painter = CommandDraw()
        self.history_manager = UserHistory()
        self.conf = self.history_manager.conf
        # client
        self.client = WudaoClient()

    # init parameters
    def param_separate(self):
        if len(sys.argv) == 1:
            self.param_list.append('h')
        else:
            for v in sys.argv[1:]:
                if v.startswith('-'):
                    self.param_list.append(v)
                else:
                    self.word += ' ' + v
        self.word = self.word.strip()

    # process parameters
    def param_parse(self):
        if len(self.param_list) == 0:
            return
        # help
        if '-h' in self.param_list or '--help' in self.param_list:
            print('Usage: wd [OPTION]... [WORD]')
            print('Youdao is wudao, a powerful dict.')
            print(
                '-k, --kill             kill the server process       (退出服务进程)'
            )
            print(
                '-h, --help             display this help and exit    (查看帮助)')
            print(
                '-s, --short            do or don\'t show sentences    (简明/完整模式)'
            )
            print(
                '-i, --inter            interaction mode              (交互模式)')
            print(
                '-n, --note             save/not save to notebook     (保存/不保存到生词本)'
            )
            print(
                '-v, --version          version info                  (版本信息)')
            print('生词本文件: ' + os.path.abspath('./usr/') + '/notebook.txt')
            print('查询次数: ' + os.path.abspath('./usr/') + '/usr_word.json')
            #print('-o, --online-search          search word online')
            exit(0)
        # interaction mode
        if '-i' in self.param_list or '--inter' in self.param_list:
            print('进入交互模式。直接键入词汇查询单词的含义。下面提供了一些设置:')
            print(':help                    本帮助')
            print(':note [filename]         设置生词本的名称')
            print(':long                    切换完整模式(:short切换回去)')
            self.interaction()
            sys.exit(0)
        # close server
        if '-k' in self.param_list or '--kill' in self.param_list:
            self.client.close()
            sys.exit(0)
        # version
        if '-v' in self.param_list or '--version' in self.param_list:
            print('Wudao-dict, Version \033[31m2.1\033[0m, Nov 27, 2019')
            sys.exit(0)
        # conf change
        if '-s' in self.param_list or '--short' in self.param_list:
            self.conf['short'] = not self.conf['short']
            if self.conf['short']:
                print('简明模式已开启!再次键入 wd -s 切换到完整模式')
            else:
                print('完整模式已开启!再次键入 wd -s 切换到简明模式')
        if '-n' in self.param_list or '--note' in self.param_list:
            self.conf['save'] = not self.conf['save']
            if self.conf['save']:
                print('保存到生词本开启。路径:%s' % (self.history_manager.NOTE_NAME))
            else:
                print('保存到生词本关闭。再次键入 wd -n 开启')
        self.history_manager.save_conf(self.conf)
        # word check
        if not self.word:
            print('Usage: wd [OPTION]... [WORD]')
            exit(0)

    # query word
    def query(self, word, notename='notebook'):
        word_info = {}
        is_zh = False
        if word:
            if not is_alphabet(word[0]):
                is_zh = True
        # 1. query on server
        word_info = None
        server_context = self.client.get_word_info(word).strip()
        if server_context != 'None':
            word_info = json.loads(server_context)
        # 2. search in online cache first
        if not word_info:
            word_info = self.history_manager.get_word_info(word)
        # 3. online search
        if not word_info:
            try:
                # online search
                from src.WudaoOnline import get_text, get_zh_text
                from urllib.error import URLError
                import bs4
                import lxml
                if is_zh:
                    word_info = get_zh_text(word)
                else:
                    word_info = get_text(word)
                if not word_info['paraphrase']:
                    print('No such word: %s found online' %
                          (self.painter.RED_PATTERN % word))
                    return
                # store struct
                self.history_manager.add_word_info(word_info)
            except ImportError:
                print('Word not found, auto Online search...')
                print('You need install bs4, lxml first.')
                print('Use ' +
                      self.painter.RED_PATTERN % 'sudo pip3 install bs4 lxml' +
                      ' or get bs4 online.')
                return
            except URLError:
                print('Word not found, auto Online search...')
                print('No Internet : connection time out.')
                return
            except socket.error as socketerror:
                print("Error: ", socketerror)
                return
        # 4. save note
        if self.conf['save'] and not is_zh:
            self.history_manager.save_note(word_info, notename)
        # 5. draw
        if word_info:
            if is_zh:
                self.painter.draw_zh_text(word_info, self.conf)
            else:
                self.painter.draw_text(word_info, self.conf)
                self.history_manager.add_item(word_info)
        else:
            print('Word not exists.')

    # interaction mode
    def interaction(self):
        self.conf = {'save': True, 'short': True, 'notename': 'notebook'}
        while True:
            try:
                inp = input('~ ')
            except EOFError:
                sys.exit(0)
            if inp.startswith(':'):
                if inp == ':quit':
                    print('Bye!')
                    sys.exit(0)
                elif inp == ':short':
                    self.conf['short'] = True
                    print('简明模式(例句将会被忽略)')
                elif inp == ':long':
                    self.conf['short'] = False
                    print('完整模式(例句将会被显示)')
                elif inp == ':help':
                    print(':help                    本帮助')
                    print(':quit                    退出')
                    print(':note [filename]         设置生词本的名称')
                    print(':long                    切换完整模式(:short切换回去)')
                elif inp.startswith(':note'):
                    vec = inp.split()
                    if len(vec) == 2 and vec[1]:
                        self.conf['notename'] = vec[1]
                        print('生词本指定为: ./usr/%s.txt' % (vec[1]))
                    else:
                        print('Bad notebook name!')
                else:
                    print('Bad Command!')
                continue
            if inp.strip():
                self.query(inp.strip(), self.conf['notename'])
예제 #6
0
class WudaoCommand:
    def __init__(self):
        # Member
        self.word = ""
        self.param_list = []
        self.draw_conf = True
        self.is_zh = False
        # Init
        self.param_separate()
        self.painter = CommandDraw()
        self.history_manager = UserHistory()
        # client
        self.client = WudaoClient()

    # init parameters
    def param_separate(self):
        if len(sys.argv) == 1:
            self.param_list.append("h")
        else:
            for v in sys.argv[1:]:
                if v.startswith("-"):
                    self.param_list.append(v[1:])
                else:
                    self.word += " " + v
        self.word = self.word.strip()
        if self.word:
            if not is_alphabet(self.word[0]):
                self.is_zh = True

    # process parameters
    def param_parse(self):
        if len(self.param_list) == 0:
            return
        if "h" in self.param_list or "-help" in self.param_list:
            print("Usage: wd [OPTION]... [WORD]")
            print("Youdao is wudao, A powerful dict.")
            print("-k, --kill                   kill the server process")
            print("-h, --help                   display this help and exit")
            print("-s, --short-desc             show description without the sentence")
            print("-o, --online-search          search word online")
            exit(0)
        # close server
        if "k" in self.param_list or "-kill" in self.param_list:
            self.client.close()
            sys.exit(0)
        # short conf
        if "s" in self.param_list or "-short-desc" in self.param_list:
            self.draw_conf = False
        if not self.word:
            print("Usage: wdd [OPTION]... [WORD]")
            exit(0)

    # query word
    def query(self):
        # query on server
        server_context = self.client.get_word_info(self.word).strip()
        if server_context != "None":
            wi = json.loads(server_context)
            if self.is_zh:
                self.painter.draw_zh_text(wi, self.draw_conf)
            else:
                self.history_manager.add_item(self.word)
                self.painter.draw_text(wi, self.draw_conf)
        else:
            # Online search
            if "o" in self.param_list or "-online-search" in self.param_list:
                try:
                    from src.WudaoOnline import get_text, get_zh_text
                    from urllib.error import URLError

                    if self.is_zh:
                        word_info = get_zh_text(self.word)
                    else:
                        word_info = get_text(self.word)
                    if not word_info["paraphrase"]:
                        print("No such word: %s found online" % self.word)
                        exit(0)
                    self.history_manager.add_item(self.word)
                    if not self.is_zh:
                        self.history_manager.add_word_info(word_info)
                        self.painter.draw_text(word_info, self.draw_conf)
                    else:
                        self.painter.draw_zh_text(word_info, self.draw_conf)
                except ImportError:
                    print("You need install bs4 first.")
                    print("Use 'pip3 install bs4' or get bs4 online.")
                except URLError:
                    print("No Internet : Please check your connection first")
            else:
                # search in online cache first
                word_info = self.history_manager.get_word_info(self.word)
                if word_info:
                    self.history_manager.add_item(self.word)
                    self.painter.draw_text(word_info, self.draw_conf)
                else:
                    print("Error: no such word :" + self.word)
                    print("You can use -o to search online.")