從輝今天跟大家分享了檔案讀寫的方法,以下是今天的範例:
#!/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()
這個程式是由缺陷的,大家有發現嗎?