Exemplo n.º 1
0
    def get_score(self):
        """
        获得成绩列表
        :return: json array
        """
        html = self.__get_score_html()
        soup = BeautifulSoup(html)
        div = soup.find_all('div', class_='Section1')[0]
        tag_ps = div.find_all('p')
        del tag_ps[0]
        result = []
        '''
        #one object
        {
           'year':'第一学期',
           'score_list':[
                {
                    'id':'0800040',
                    'name':'C++'
                    'type':'必修',
                    'xuefen':'1',
                    'score':'95',
                    'remark':'重修'
                }
           ]
        }
        '''
        # 最后一个为第二课堂学分,删除之
        tables = soup.find_all('table', attrs={'class': 'MsoTableGrid', 'border': '1'})
        del tables[len(tables) - 1]
        # 第x个学期
        year_num = 1
        for table in tables:
            try:
                trs = table.find_all('tr')

                tern_info = {
                    'year': year_num,
                    'score_list': []
                }
                # 遍历每一列
                for tr in trs:
                    tds = tr.find_all(self.__get_td)
                    if len(tds) == 0:
                        continue
                    lesson_info = {
                        'id': _.trim(tds[0].get_text()),
                        'name': _.trim(tds[1].get_text()),
                        'type': _.trim(tds[2].get_text()),
                        'xuefen': _.trim(tds[3].get_text()),
                        'score': _.trim(tds[4].get_text()),
                        'remark': _.trim(tds[5].get_text())
                    }

                    tern_info['score_list'].append(lesson_info)
                year_num += 1
                result.append(tern_info)
            except Exception as e:
                _.d(e.message)
        return result
Exemplo n.º 2
0
    def get_electricity_info(self, apart_id, meter_room):
        """get electricity info

            :param apart_id: 栋数
            :param meter_room: 宿舍号
        """
        apart_id = str(apart_id)
        meter_room = str(meter_room)
        try:
            content = LifeService._get_electricity_info_html(apart_id, meter_room)
        except KeyError as e:
            _.d(e.message)
            result = {
                'response': None
            }
            return _.to_json_string(result)
        soup = BeautifulSoup(content)
        tags = soup.find_all(name='span', class_='STYLE7')
        result = {
            'response': {
                'apart': _.trim(tags[0].string),
                'apart_id': _.trim(tags[1].string),
                'used': _.trim(tags[2].string),
                'left': _.trim(tags[3].string),
                'update_time': _.trim(tags[4].string)
            }
        }
        return _.to_json_string(result)
Exemplo n.º 3
0
def search_wiki(word = 'クロマニョン人'):
	ans = ''
	try:
		converted_word = urllib.parse.quote_plus(word, encoding="utf-8")
		wiki_url = ''.join(["https://ja.wikipedia.org/wiki/", converted_word])
		soup = get_bs4soup(wiki_url)
		ptext = soup.findAll("p")
		pstr =  ''.join([p.get_text() for p in ptext])
		ans = re.sub(re.compile('\<.+\>'), '' , pstr)
		ans = ans.replace('この記事には複数の問題があります。改善やノートページでの議論にご協力ください。', '').replace('■カテゴリ / ■テンプレート', '')
		anslist = [re.sub(re.compile('\[.+\]'), '' , s) for s in ans.split('。')]
		ans = ''.join(['。'.join(anslist[:8]), '。']).replace('。。', '。')
		return ans
	except Exception as e:
		d(e)
		return ''.join(['\'', word, '\'に一致する語は見つかりませんでした。'])
Exemplo n.º 4
0
 def on_disconnect(self, notice):
     d(notice, 'disconnect')
     return False
Exemplo n.º 5
0
    def srtr(self):
        s = self.s
        status = ''
        ans = ''
        last = ''
        answord = ''
        wordsList = []
        kanasList = []
        wordsList = self.srtrdb.word_stream.split('<JOIN>')
        kanasList = self.srtrdb.kana_stream.split('<JOIN>')
        self.game_mode = self.srtrdb.mode
        self.time = self.srtrdb.tmp_time
        self.len_rule = self.srtrdb.len_rule
        if any(
            [rev_srtr in s for rev_srtr in ['逆しりとり', '頭取り', 'あたまとり', 'あたま取']]):
            self.game_mode = 'reverse'
            self.event = 'restart'
        elif 'しりとり' in s:
            self.game_mode = 'normal'
            self.event = 'restart'
        else:
            pass
        turncnt = len(wordsList)
        # TODO]アポストロフィに無理やり対応(すごい例外)
        s = s.replace('海未', '園田海未')
        if "μ's" in s:
            rawnoun = "μ's"
            kana = 'ミューズ'
        else:
            rawNouns = natural_language_processing.MA.get_mecab(
                s,
                form=['名詞'],
                exception={'数', '接尾', '非自立', '接続助詞', '格助詞', '代名詞'})
            kanaNouns = natural_language_processing.MA.get_mecab(
                s,
                mode=8,
                form=['名詞'],
                exception={'数', '接尾', '非自立', '接続助詞', '格助詞', '代名詞'})
            if not rawNouns:
                status = 'alert_nonoun'
            else:
                rawnoun = rawNouns[0]
                kana = kanaNouns[0]
                if kana == '*':
                    status = 'alert_nonoun'
        if not status:
            try:
                cleaned_noun = re.sub(re.compile('[!-@[-`{-~]'), '', kana)
                gobi = cleaned_noun[-1:]
                if gobi == 'ー':
                    gobi = cleaned_noun.replace('ー', '')[-1:]
                gotou = cleaned_noun[:1]
                gobi = gobi.replace('ャ', 'ヤ').replace('ュ', 'ユ').replace(
                    'ョ', 'ヨ').replace('ッ', 'ツ').replace('ィ', 'イ').replace(
                        'ァ', 'ア').replace('ェ', 'エ').replace('ゥ', 'ウ').replace(
                            'ォ',
                            'オ').replace('ヵ',
                                         'カ').replace('ヶ',
                                                      'ケ').replace('ヮ', 'ワ')
                if self.game_mode == 'reverse':
                    gotou, gobi = gobi, gotou
                word = {}
                lenword = len(kana)
                last = ''
                try:
                    if self.game_mode != 'reverse':
                        last = kanasList[-1][-1]
                        if last == 'ー':
                            last = kanasList[-1].replace('ー', '')[-1]
                    else:
                        last = kanasList[-1][0]
                    last = last.replace('ャ', 'ヤ').replace('ュ', 'ユ').replace(
                        'ョ', 'ヨ').replace('ッ', 'ツ').replace('ィ', 'イ').replace(
                            'ァ',
                            'ア').replace('ェ', 'エ').replace('ゥ', 'ウ').replace(
                                'ォ', 'オ').replace('ヵ', 'カ').replace(
                                    'ヶ', 'ケ').replace('ヮ', 'ワ')
                except Exception as e:
                    d(e, 'srtr')
                if not last:
                    wordsList.append(rawnoun)
                    kanasList.append(kana)
                if self.event == 'showlist':
                    return wordsList
                elif self.event == 'restart':
                    wordsList = []
                    kanasList = []
                    try:
                        num = re.match("\d*", s)
                        extracted = num.group()
                        self.len_rulelen_rule = int(extracted)
                        is_changed = True
                        s = s.replace('文字', '').replace('字',
                                                        '').replace('以上', '')
                    except Exception as e:
                        len_rule = 1
                    if gobi == 'ン':
                        rawnoun = 'しりとり'
                        kana = 'シリトリ'
                        gobi = 'リ'
                    wordsList.append(rawnoun)
                    kanasList.append(kana)
                    if self.game_mode != 'reverse':
                        status = 'start_normal'
                    else:
                        status = 'start_reverse'
                elif lenword < self.len_rule and rawnoun != 'しりとり':
                    status = 'alert_short'
                else:
                    if last != gotou:
                        if self.game_mode != 'reverse':
                            status = 'alert_miss'
                        else:
                            status = 'alert_miss_reverse'
                    elif rawnoun in wordsList:
                        status = 'win_double'
                    elif gobi == 'ン':
                        status = 'win_N'

                    else:
                        wordsList.append(rawnoun)
                        kanasList.append(kana)
                        LoseFlag = False
                        # LoseFLAG
                        if turncnt > 25:
                            LoseFlag = True
                        with db.atomic():
                            if LoseFlag:
                                answords = TFIDFModel.select().where(
                                    TFIDFModel.yomi.startswith(gobi),
                                    TFIDFModel.yomi.endswith('ン'),
                                    TFIDFModel.hinshi << ['名詞', '固有名詞'],
                                    ~TFIDFModel.hinshi << ['数']).order_by(
                                        TFIDFModel.df.desc()).limit(50)
                                answord = self.choose_answord(answords)
                            else:
                                if self.game_mode != 'reverse':
                                    select_words = TFIDFModel.select().where(
                                        TFIDFModel.yomi.startswith(gobi),
                                        ~TFIDFModel.yomi.contains('*'),
                                        ~TFIDFModel.yomi.endswith('ン'),
                                        TFIDFModel.hinshi << ['名詞', '固有名詞'],
                                        ~TFIDFModel.hinshi2 << ['数', '	接尾'])
                                else:
                                    select_words = TFIDFModel.select().where(
                                        TFIDFModel.yomi.endswith(gobi),
                                        ~TFIDFModel.yomi.contains('*'),
                                        TFIDFModel.hinshi << ['名詞', '固有名詞'],
                                        ~TFIDFModel.hinshi2 << ['数', '接尾'])
                                answords = select_words.order_by(
                                    TFIDFModel.df.desc()).limit(300)
                                answord = self.choose_answord(answords)
                        if answord.word in wordsList:
                            status = 'lose_double'
                        elif answord.yomi[-1] == 'ン':
                            status = 'lose_N'
                        else:
                            if self.game_mode != 'reverse':
                                status = 'return_normal'
                                next_char = answord.yomi[-1]
                            else:
                                status = 'return_reverse'
                                next_char = answord.yomi[0]
                            anskana = answord.yomi
                            if next_char == 'ー':
                                next_char = answord.yomi[-2]
                                anskana = answord.yomi[:-1]
                            wordsList.append(answord.word)
                            kanasList.append(anskana)
            except Exception as e:
                d(e, 'srtr')
                wordsList = []
                kanasList = []
        with db.atomic():
            self.srtrdb.name = self.user
            self.srtrdb.mode = self.game_mode
            self.srtrdb.word_stream = '<JOIN>'.join(wordsList)
            self.srtrdb.kana_stream = '<JOIN>'.join(kanasList)
            self.srtrdb.len_rule = self.len_rule
            self.srtrdb.tmp_time = datetime.utcnow()
            self.srtrdb.save()
        p(status)
        if last:
            last = last.replace('ャ', 'ヤ').replace('ュ', 'ユ').replace(
                'ョ', 'ヨ').replace('ッ', 'ツ').replace('ィ', 'イ').replace(
                    'ァ', 'ア').replace('ェ', 'エ').replace('ゥ', 'ウ').replace(
                        'ォ', 'オ').replace('ヵ',
                                          'カ').replace('ヶ',
                                                       'ケ').replace('ヮ', 'ワ')
        if not status:
            ans = '思いつきませんでした。悔しいですけど、私の負けです。\END'
        elif status == 'start_normal':
            ans = 'いいですね。' + str(
                self.len_rule
            ) + '字以上でしりとりをしましょう。\nそれでは、「' + rawnoun + '」から開始です。'
        elif status == 'start_reverse':
            ans = 'いいですね。' + str(
                self.len_rule
            ) + '字以上で逆しりとりしましょう。\nそれでは、「' + rawnoun + '」から開始です。'
        elif status == 'alert_nonoun':
            ans = '名詞の単語が見あたりません。他の単語はありませんか?\MISS'
        elif status == 'alert_short':
            ans = '「' + rawnoun + '」ですね。' + str(
                self.len_rule) + '字縛りなので、字数が短いです。\n「しりとりおわり」で降参しても構いません。\MISS'
        elif status == 'alert_miss':
            ans = 'その言葉ではだめです。\n「' + last + '」ではじめる別の単語でお願いします。「しりとりおわり」で終了してもOKです。\MISS'
        elif status == 'alert_miss_reverse':
            ans = 'その言葉ではだめです。\n「' + last + '」でおわる別の単語でお願いします。「しりとりおわり」で終了してもOKです。\MISS'
        elif status == 'lose_double':
            ans = '「' + rawnoun + '」ですね。' + gobi + '...\n' + answord.word + ' ですッ!! あ、既に出ていた単語でした...。くっ、私の負けです。\END'
        elif status == 'lose_N':
            ans = '「' + rawnoun + '」ですね。' + gobi + '...\n' + answord.word + ' ですッ!! あ、「ン」がついてしまいました...。くっ、私の負けです。\END'
        elif status == 'win_double':
            ans = '「' + rawnoun + '」ですね。' + gobi + '...\n' + 'その言葉は既に使われましたよ。私の勝利ですっ!! \END'
        elif status == 'win_N':
            ans = '「' + rawnoun + '」ですね。' + gobi + '...\n' + '「ン」で終わりましたね。私の勝利です。 \END'
        elif status == 'return_normal':
            ans = '「' + rawnoun + '」ですね。' + gobi + '...\n' + answord.word + '(' + answord.yomi + ')' + ' ですっ!! 次の頭文字は「' + next_char + '」ですよ。'
        elif status == 'return_reverse':
            ans = '「' + rawnoun + '」ですね。' + gobi + '...\n' + answord.word + '(' + answord.yomi + ')' + ' ですっ!! 次の末尾の文字は「' + next_char + '」ですよ。'
        else:
            ans = 'エラーが発生しました。管理者にお問い合わせください。[{status}] \END'.format(
                status=status)
        return ans
Exemplo n.º 6
0
    def get_score(self):
        """
        获得成绩列表
        :return: json array
        """
        html = self.__get_score_html()
        soup = BeautifulSoup(html)
        div = soup.find_all('div', class_='Section1')[0]
        tag_ps = div.find_all('p')
        del tag_ps[0]
        result = []
        '''
        #one object
        {
           'year':'第一学期',
           'score_list':[
                {
                    'id':'0800040',
                    'name':'C++'
                    'type':'必修',
                    'xuefen':'1',
                    'score':'95',
                    'remark':'重修'
                }
           ]
        }
        '''
        # 最后一个为第二课堂学分,删除之
        tables = soup.find_all('table',
                               attrs={
                                   'class': 'MsoTableGrid',
                                   'border': '1'
                               })
        del tables[len(tables) - 1]
        # 第x个学期
        year_num = 1
        for table in tables:
            try:
                trs = table.find_all('tr')

                tern_info = {'year': year_num, 'score_list': []}
                # 遍历每一列
                for tr in trs:
                    tds = tr.find_all(self.__get_td)
                    if len(tds) == 0:
                        continue
                    lesson_info = {
                        'id': _.trim(tds[0].get_text()),
                        'name': _.trim(tds[1].get_text()),
                        'type': _.trim(tds[2].get_text()),
                        'xuefen': _.trim(tds[3].get_text()),
                        'score': _.trim(tds[4].get_text()),
                        'remark': _.trim(tds[5].get_text())
                    }

                    tern_info['score_list'].append(lesson_info)
                year_num += 1
                result.append(tern_info)
            except Exception as e:
                _.d(e.message)
        return result