def ILEloop(R, A, structure, is_print=True): cnt = 1 total_strong_connected_ls = [] altR, structure, StrProgress, strong_connected_ls = identify_level_elements( R, A, structure, is_print) S = len(altR) strS = str(S) if strong_connected_ls: total_strong_connected_ls.append(strong_connected_ls) while StrProgress < S: if cnt > 50: p('error cnt over', is_print=is_print) return structure.append('ERR') else: p('continue... progress >> ', StrProgress, '/', strS, ' cnt', cnt, is_print=is_print) cnt += 1 altR, structure, StrProgress, strong_connected_ls = identify_level_elements( altR, A, structure, is_print) if strong_connected_ls: total_strong_connected_ls.append(strong_connected_ls) else: p('Finished !! ', StrProgress, '/', strS, is_print=is_print) p('strong-connect-pair: ', total_strong_connected_ls) p(structure) return structure
def extract_face(faces, i): #(四角の左上のx座標, 四角の左上のy座標, 四角の横の長さ, 四角の縦の長さ) pos = faces[i] bottom = pos[1]+pos[3] right = pos[0]+pos[2] if not (pos[1] < 0 or right > height or pos[0] < 0 or bottom > width): cvimg = original_cvimg result_dic['extracted'] = {} result_dic['extracted'][i] = {} pos_dic = {} pos_dic['left'] = int(pos[0]) pos_dic['top'] = int(pos[1]) pos_dic['bottom'] = int(bottom) pos_dic['right'] = int(right) pos_dic['height'] = int(pos[2]) pos_dic['width'] = int(pos[3]) result_dic['extracted'][i]['pos'] = pos_dic face_icon = cvimg[pos_dic['top']: pos_dic['bottom'], pos_dic['left']: pos_dic['right']] if not frame_setting is None: framed_cvimg = frame_image(cvimg, pos = result_dic['extracted'][i]['pos'],frame_setting = frame_setting) show_image(framed_cvimg, filename = '') json = {} json['pos'] = result_dic['extracted'][i]['pos'] p(json) result_dic['extracted'][i]['icon_cvimg'] = face_icon result_dic['extracted'][i]['icon_id'] = save_image_sql(cvimg = face_icon, filename = ''.join([str(_id), '_icon', str(i)]), url = _id, owner = None, json = json, compression_quality = 70, compression_format = 'jpg') is_show = False if is_show: show_image(face_icon, filename = result_dic[i]['icon_id'])
def get_googlemap(url = 'https://notendur.hi.is/~sfg6/google_maps_example/'): USER_AGENT = {'User-Agent': 'Mozilla/5.0'} #Needed to prevent 403 error phantomjs_path = '/usr/local/bin/phantomjs' driver = webdriver.PhantomJS(executable_path=phantomjs_path, service_log_path=os.path.devnull, desired_capabilities={'phantomjs.page.settings.userAgent':USER_AGENT}) # get a HTML response driver.set_window_size(1280, 800) driver.get(url) html = driver.page_source.encode('utf-8') # more sophisticated methods may be available soup = bs4.BeautifulSoup(html, 'lxml') p(soup) time.sleep(5) driver.save_screenshot('test_google_maps_api_screenshot.png')
def get_dl_links(url = "https://www.jstage.jst.go.jp/browse/jspa1962/-char/ja/", extention = 'pdf', except_str = 'pub', DIR = DATADIR, sleep_time = 1): abs_filename_ls = [] try: soup = get_bs4soup(url) links = soup.findAll('a') download_urls = [href for href in [link.get('href') for link in links] if href and extention in href and not except_str in href] BASE_URL = '/'.join(url.split('/')[:3]) downloads_cnt = len(download_urls) error_cnt = 0 p(''.join([str(downloads_cnt), '件のファイルをダウンロードします。'])) for i in range(downloads_cnt): time.sleep(sleep_time) try: target_url = ''.join([BASE_URL, download_urls[i]]) p(target_url) filename = '.'.join([target_url.split('/')[-2], extention]) abs_filename_ls.append(_.download_file(url = target_url, DIR = DIR, filename = filename)) except: error_cnt += 1 pass p(''.join(['COMPLETE:', str(i-error_cnt+1), '/', str(downloads_cnt), '\tERR:', str(error_cnt)])) return abs_filename_ls except Exception as e: p(e) return abs_filename_ls
def get_listmembers_all(self, username, listname): try: return [ UserObject.screen_name for UserObject in tweepy.Cursor( self.twtr_api.list_members, username, listname).items() ] except tweepy.error.TweepError as e: if e.api_code == '34': if username == self.bot_id: p(listname, 'MAKE the LIST!!') # self.is_create_list_success(name = listname) return [] except: return []
def extract_ss(url = 'http://www.lovelive-ss.com/?p={}'): soup = get_bs4soup(url) title = soup.find('h1', class_="entry-title") if title is None: return None else: p(title.get_text(), url) try: ss_contents = soup.find("div", class_ = "entry-content").find_all("dd", class_ ="t_b") except: return None def op_soup(content): a_conts = content.find_all('a') [a_cont.extract() for a_cont in a_conts if not a_cont is None] return content.get_text() s_ls = [op_soup(ss_content) for ss_content in ss_contents] return s_ls
def user_stream(self, srf, q, lock, events): # _.reconnect_wifi() p('start user_stream') auth = self.twtr_auth stream = tweepy.Stream(auth=auth, listener=StreamListener(srf, q, lock, events), async=False, timeout=180) stream.userstream(stall_warnings=True, _with=None, replies=None, track=None, locations=None, encoding='utf8', async=True) p('waiting stop event') events.stop.wait() p('stopping user_stream') stream.running = False
def on_limit(self, track): p(self.bot_id, 'track', track) return True
def keep_alive(self): p(self.bot_id, 'keep_alive...') self.events.ping.set() return True
def __del__(self): p(self.bot_id, 'stopping streaming...')
def on_timeout(self): p('timeout...') return False
def simplifyC( text='S1→S5\nS2→S1\nS2→S3\nS2→S4\nS3→S5\nS3→S4\nS4→S3\nS6→S2\nS6→S5', arrow='→', is_print=True): chunk = text.split('\n') pairs = [arg.split(arrow) for arg in chunk] words = list(chain.from_iterable(pairs)) # print(words) factors = f7(words) factors_cnt = len(factors) p('抽出された要素は以下の通りです。', is_print=is_print) p(factors, is_print=is_print) z = np.zeros((factors_cnt, factors_cnt)) I = np.identity(factors_cnt) causels = [pair[0] for pair in pairs] effectls = [pair[1] for pair in pairs] causeN = [factors.index(cause) for cause in causels] effectN = [factors.index(effect) for effect in effectls] z[causeN, effectN] = 1 adjacency_matrix = z reach_ability_matrix = adjacency_matrix + I # Identifying process of the 1st level lements R = [] A = [] p('boolean演算を実行します。', is_print=is_print) RAM = prd_boolen_matrix(reach_ability_matrix) p('boolにおいて(A+I)^r = (A+I)^(r+1) /= A+I \nとなる可到達行列は以下のとおりです。', is_print=is_print) p(RAM, is_print=is_print) for Si in range(factors_cnt): Ai = RAM[:, Si] Ri = RAM[Si] A.append(npwhere(Ai)) R.append(npwhere(Ri)) p('行列から抽出した集合は以下のとおりです。', is_print=is_print) p('A', is_print=is_print) p(A, is_print=is_print) p('R', is_print=is_print) p(R, is_print=is_print) structure = [] Level = [] structure = ILEloop(R, A, structure, is_print=is_print) p(structure, is_print=is_print) structureName = [] p('++++result structure is as following !!++++', is_print=is_print) ans_ls = [] ans_ls.append('######EFFECT######') for level in structure: level_name = [] for num in level: level_name.append(factors[num]) ans_ls.append('↑↑↑↑↑↑↑') [ans_ls.append(name) for name in level_name] structureName.append(level_name) ans_ls.append('######CAUSE######') ans = '\n'.join(ans_ls) p(ans) return structureName, structure
def on_error(self, status_code): p(status_code, 'cannot get') return False
def on_warning(self, notice): p(notice, 'warning') return True
def identify_level_elements(R, A, structure, is_print): # dirtyCode... リスト内包表記で要修正 p('~~~~~~~~~~~~~~~~~~~~~~~~~~~', is_print=is_print) S = len(R) strS = str(S) Level = [] structureN = [] RcapA = calcRcapA(R, A, S) p('RcapA', is_print=is_print) p(RcapA, is_print=is_print) for i in range(S): Ri = R[i] RiAi = RcapA[i] if RiAi == Ri: Level.append(Ri) if Ri: structureN.append(i) # try: altR = [] p('Level', is_print=is_print) Level = [level for level in Level if level] p(Level, is_print=is_print) p('structureN', is_print=is_print) p(structureN, is_print=is_print) avoidLevel = flatten(Level) strong_connected_ls = [] # check discrete or not if len(Level) != 1: p('parallel cause-effect... ', is_print=is_print) for level in Level: if len(level) > 1: p(level, ' Not Discrete, Strongly connected...', is_print=is_print) strong_connected_ls.append(level) Level.remove(level) for i in range(S): Ri = R[i] altRi = [r for r in Ri if r not in avoidLevel] altR.append(altRi) p('altR', is_print=is_print) p(altR, is_print=is_print) structure.append(structureN) structure = [structure for structure in structure if structure != []] p('whole_structure', is_print=is_print) p(structure, is_print=is_print) StrProgress = len(flatten(structure)) return altR, structure, StrProgress, strong_connected_ls
# import urllib.parse # urlencode # import http # import http.cookiejar # opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())) USER_AGENT = {'User-Agent': 'Mozilla/5.0'} #Needed to prevent 403 error phantomjs_path = '/usr/local/bin/phantomjs' login_url = 'https://mobile.twitter.com/session/new' # img_url = 'https://twitter.com/messages/media/772747782637563907' img_url = 'https://ton.twitter.com/1.1/ton/data/dm/772785678509760515/772785678547423232/iEUEceDa.jpg' driver = webdriver.PhantomJS(executable_path=phantomjs_path, service_log_path=os.path.devnull, desired_capabilities={'phantomjs.page.settings.userAgent':USER_AGENT}) driver.get(img_url) try: loginid = driver.find_element_by_id('session[username_or_email]') except: p('log-in') tw_id, tw_pw = 'LiveAI_Rin','705216130' driver.get(login_url) # ログインページを開く html = driver.page_source.encode('utf-8') loginid = driver.find_element_by_id('session[username_or_email]') password = driver.find_element_by_id('session[password]') loginid.send_keys(tw_id) password.send_keys(tw_pw) driver.find_element_by_name('commit').click() driver.get(img_url) time.sleep(1) driver.save_screenshot('DMimg.png') driver.quit() # p(search_weblioEJJE(word = 'some')) # range(4538, 8000): # reg = natural_language_processing.RegexTools()
Bannerfilename=user.abs_banner_filename) return True except Exception as e: _.log_err() return False if __name__ == '__main__': twf = TwtrTools('LiveAI_Hanamaru') # twf.send(ans = '書込凍結のbotを捜索中(表示が出てれば無事です)', screen_name = 'LiveAI_Alpaca', mode = 'tweet') # twf.update_profile(name = '実験垢@', description='', location='', url = '', filename = '', BGfilename = '', Bannerfilename = '') # twf.imitate('LiveAI_Umi') # p() set_time = datetime.now(JST).strftime('%Y%m%d%H%M%S') p(set_time.strftime('%Y%m%d%H%M%S')) # st = twf.send(ans = 'test23', screen_name = 'kaihatsu_paka', mode = 'tweet') # if st: # p(st.id_str) # user = twf.get_userinfo(screen_name = 'kaihatsu_paka') # p(user) # user.name # user_id = user.id_str #'id': 768871329332203522, # a = twf.twtr_api.me() # a = twf.twtr_api.get_user(screen_name = 'LiveAI_Umi') # a = operate_sql.BotProfile() # p(a.location) # p(a.__dict__) # p(hasattr( a, 'name')) # objs = twf.get_followers_all('LiveAI_Maki')
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
def on_exception(self, exception): p(exception, self.bot_id, 'exception') return False
cvimg = overlay_on_part(src_image = cvimg, overlay_image = overlay_image_resized, posX = pos['left'], posY = pos['top']) # framed_id = save_image_sql(cvimg = cvimg, filename = ''.join([_id, '_framed', str(LTRB)]), url = _id, owner = None, compression_quality = 70, compression_format = 'jpg')` return cvimg if __name__ == '__main__': sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') filename = "/XXXXXX" # filename2 = /XXXXXX' # make_qrcode(data = 'hello') _id = '832b32bb-3e2d-4bbf-9217-ff358fa8a317' # cvimg = read_image_sql(_id = _id) # p(passzbar(cvimg)) # _ID = save_image_sql(cvimg, filename = None, url = 'MjAxNjA5MDUwMzE5MzYvNDUyNDA=', owner = None, compression_quality = 70, compression_format = 'jpg') result = recognize_faceimage(_id = '7aa33bfe-e6c0-4156-a4d0-7e53e88b1dd1', is_show = True,cascade_lib = cascade_lib_anime) p(result) # p(uuid.uuid4()) # p(uuid.uuid4().hex) # make_qrcode(data = 'hello', owner = None) # height, width = img.shape[:2] # p(height * width) # compression_params = [cv2.IMWRITE_JPEG_QUALITY, 70] # retval, buf = cv2.imencode('jpg', img, compression_params) # if not retval: # raise ValueError('The Given image could not be converted to BMP binary data') # height, width = buf.shape[:2] # p(height * width) # # convert buf from numpy.ndarray to bytes # binary = buf.tobytes() # BinaryBank.create_or_get(filename = 'test',data = binary) # p(type(img))
json['detection'] = 'anime' json['prediction'] = result_dic['anime']['extracted'][i]['label'] result_dic['anime']['extracted'][i]['framed_id'] = opencv_functions.save_image_sql(cvimg = framed_cvimg, filename = ''.join([str(_id), '_SVMdetect', result_dic['anime']['extracted'][i]['label'], '_framed', str(i)]), url = str(_id), owner = None, json = json, compression_quality = 70, compression_format = 'jpg') elif 'cat' in result_dic: result_dic['cat']['extracted'][0]['label'] = 'cat' json['detection'] = 'cat' frame_setting = {'thickness': 1, 'color':(204,153,153), 'scale':1.1, 'overlay_id' :'fabdb2c9-50c7-459e-9a29-94bbcdd77381'} json['frame_setting'] = frame_setting framed_cvimg = opencv_functions.frame_image(cvimg = result_dic['cat']['original_cvimg'], pos = result_dic['cat']['extracted'][0]['pos'], frame_setting = frame_setting) result_dic['cat']['extracted'][0]['framed_id'] = opencv_functions.save_image_sql(cvimg = framed_cvimg, filename = ''.join([str(_id), '_cat', '_framed', str(0)]), url = str(_id), owner = None, json = json, compression_quality = 70, compression_format = 'jpg') return result_dic if __name__ == '__main__': import sys, os, io sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') # 6海未 7真姫 filename = /XXXXXX' DIR = /XXXXXX' ans = predict_svm(_id = '7aa33bfe-e6c0-4156-a4d0-7e53e88b1dd1', is_show = 1, model = modelSVM, label = ['others', 'ことり', 'にこ', '真姫', '凛', '希', '海未', '真姫', '穂乃果', '絵里', '花陽', '雪穂']) print(ans) if 'anime' in ans: p('a') # label, img_kind, IMGfile = machine_learning_img.predictSVM(filename = filename, isShow = False, model = modelSVM, work_dir = '') # train_svm(DIR = "/XXXXXX", save_dir = DATADIR + '/lib/SVM_us3/SVMmodel3.pkl') # adrs = [DIR+clsdir for clsdir in os.listdir(DIR) if not clsdir in set(['.DS_Store'])] # print([predictSVM(filename =adr, isShow = 0, model = modelSVM)[0] for adr in adrs[:1]]) #
ans_ls.append('↑↑↑↑↑↑↑') [ans_ls.append(name) for name in level_name] structureName.append(level_name) ans_ls.append('######CAUSE######') ans = '\n'.join(ans_ls) p(ans) return structureName, structure if __name__ == '__main__': import sys import io import os sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') try: argvs = sys.argv text = argvs[1] p2 = argvs[2] mode = 'simple' except: text = 'S1→S5\nS2→S1\nS2→S3\nS2→S4\nS3→S5\nS3→S4\nS4→S3\nS6→S2\nS6→S5' p2 = 'ISM.detail()' mode = 'simple' # if text == 'demo': text = 'S1→S5\nS2→S1\nS2→S3\nS2→S4\nS3→S5\nS3→S4\nS4→S3\nS6→S2\nS6→S5' # if p2 == 'ISM.detail()': # mode = 'detail' arrow = '→' structure_name, structure = simplifyC(text, arrow, is_print=True) p(structure_name)