本週Python 08 學習-如何結構化我們的程式。
我們學習過基本的函數(function),但是很少用;現在就是時候,讓我們學習如何搭配main function 讓我們的程式具有結構化! 這是 Python 基礎學習上學習最後第二堂課了...
從輝今天跟大家分享了檔案讀寫的方法,以下是今天的範例:
#!/usr/bin/env python3 # input a file & open it while True: try: filename = input('To read a file: ') ofile = open(filename, 'rt') except: print('incorrect file, try again: ') continue break # print(ofile.read()) collection = [] word_bank = {} count_word = [] # collect each characters in ofile for line in ofile: cline = line.strip().split() for letter in cline: if not letter.isalpha(): continue collection.append(letter.lower()) for word in collection: word_bank[word] = word_bank.get(word, 0) + 1 # Sort word by alphabeta in word_bank """ 利用 dic.items 來去處key, value 並在count_word 中排序。 list 可以使用的手段比較多,所以我選擇list """ for key, value in word_bank.items(): count_word.append((key, value)) count_word.sort() # Write to a file wfile = input('Given an output file name: ') with open(wfile, 'wt') as output_file: print('Arranged by alphabet:', file=output_file) print('Words: Counting', file=output_file) for key, value in count_word: print(key, value, file=output_file) # close the file ofile.close()
這個程式是由缺陷的,大家有發現嗎?
這是coursera.org 上 "Learn to Program: The Fundamentals" by Jennifer Campbell, Paul Gries 的教學影片 這是coursera.org 上 "Learn to Program: The Fundamentals" by Jennifer Campbell, Paul Gries 的教學影片 |
Categories
All
Archives
October 2015
桃花源講堂桃花源講堂是桃園支聯會成員學習、成長的園地! |