1. 程式人生 > >《Python程式設計快速上手》實踐專案:瘋狂填詞

《Python程式設計快速上手》實踐專案:瘋狂填詞

一.專案要求:

建立一個瘋狂填詞(Mad Libs)程式,它將讀入文字檔案, 並讓使用者在該文字檔案中出現 ADJECTIVE、 NOUN、 ADVERB 或 VERB 等單詞的地方, 加上他們自己的文字。

例如,一個文字檔案可能看起來像這樣:

The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.

程式將找到這些出現的單詞, 並提示使用者取代它們。

Enter an adjective: 
silly 
Enter a noun: 
chandelier 
Enter a verb: 
screamed 
Enter a noun: 
pickup truck 

以下的文字檔案將被建立:

The silly panda walked to the chandelier and then screamed. A nearby pickup

truck was unaffected by these events.

結果應該列印到螢幕上, 並儲存為一個新的文字檔案。

二.專案原始碼

#瘋狂填詞-替換文字檔案中的單詞
'''
	方法步驟:
		1.匯入文字
		2.迴圈查詢並替換
		3.列印結果,儲存為另一個新的檔案
'''
#開啟檔案,並讀取內容
myFile = open('words.txt','r')
myNewFile = open('newwords.txt','w')
text = myFile.read()

wordsReplace = ['TEXT','HAVE','TOTAL','CHARACTERS']
wordsLength = len(wordsReplace)

#替換單詞
for i in range(wordsLength):
	print('Enter an '+ wordsReplace[i].lower()+' :')
	word = input()
	text = text.replace(wordsReplace[i],word)

#將新的文字裝入一個新的檔案中
myNewFile.write(text)

#關閉檔案
myFile.close()
myNewFile.close()