python list 簡寫

  • 190
  • 0

python list 簡寫

        #寫法一:
        rows3=[]
        for i in range(0, len(rows)):
            rows3.append(WordChange(rows[i]))
        print(rows3)
        
        print('\n')

        #寫法2:
        rows = [WordChange(str(rows[i])) for i in range(0, len(rows))]
        print(rows)
        

python

def test():
    url = 'https://www.banking.gov.tw/ch/ap/bankno_excel.jsp'
    try:
        response = requests.get(url,verify=True)
        response.encoding = 'utf-16'
        response = response.text
        global CommonResponse
        CommonResponse = response
    except:
        pass
    else:
        csvtable = []
        table= []
        rows = response.splitlines()
        logtext = 'Banking銀行總行資料\t執行時間 : ' + datetime.strftime(datetime.now(),'%Y/%m/%d %H:%M:%S ') + '\n總機構代號\t機構名稱\t機構類型\n'

        try:    
            #刪除無用標頭
            del rows[0:1]
        except:
            del rows[0:]
        
        rows = rows[0:5]
        
        #資料寫入List
        
        #寫法一:
        rows3=[]
        for i in range(0, len(rows)):
            rows3.append(WordChange(rows[i]))
        print(rows3)
        
        print('\n')

        #寫法2:
        rows = [WordChange(str(rows[i])) for i in range(0, len(rows))]
        print(rows)
        

def WordChange(TargetWord):
    try:
        return TargetWord.replace('滙','匯').replace('埗','步').replace('渋','涉').replace('邨','村').replace('浜','濱').replace('鳯','鳳').replace('劵','券').replace(' ','').replace('=','').replace('"\t"',',').replace('','').replace('','')
    except Exception as ex:
        print(TargetWord)
        print(ex)        

if __name__ == '__main__':
    test()