看板 Python 關於我們 聯絡資訊
感覺起來這個問題很蠢 這是讀取榜單 然後計算該校多少人進這間大學的程式 不過我遇到一個問題 他for迴圈只會執行print string 這行 等迴圈執行完後才執行print 'ss' 為什麼會這樣呢? 我所學告訴我應該print string和print 'ss' 執行次數應該一樣 以下是程式碼 -------------------------------------------------------- #coding=big5 forCount={} ftr=open('abcd.txt') try: for string in[ftr.read()]: print string print 'ss' a=string.index('國') b=string.index('學')+3 string=string[a+1:b-a-1] print string+'x' if string in forCount: forCount[string]+=1 else: forCount.update({string:1}) except Exception: print "ERROR" finally: ftr.close() print forCountfor (key,value) in forCount.items(): print key+':'+str(value)raw_input() -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.116.129.56 ※ 編輯: ya790206 來自: 59.116.129.56 (08/08 22:03)
subook:我猜 [ftr.read()] 裡只有一個東西,也就是整個檔案內容 08/08 22:29
subook:因此 for 也只執行了一次 08/08 22:32
subook:你可能是要用 readline 之類的... 08/08 22:32
subook:readlines 08/08 22:34
ya790206:的確[ftr.read()] 裡只有一個東西,我搞錯用法了 08/08 23:07