標籤:style span IV regex cti input NPU eve utf-8
建立一個瘋狂填詞(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 # coding=utf-8 2 import re 3 # 開啟檔案 4 wfile = open(‘sentence.txt‘,‘r‘) 5 words = wfile.read() 6 wfile.close() 7 print(words) 8 #正則讀取單詞並依次替換單詞 9 wRegex = re.compile(r‘\w[A-Z]+‘)10 for content in wRegex.findall(words):11 replaceContent= input(‘Enter a %s:\n‘%content)12 #print(content)13 #print(replaceContent)14 regex = re.compile(content) #將匹配出的單詞作為正則尋找規則,再詞尋找並用輸入的內容替換15 words=regex.sub(replaceContent,words,1) # 替換的內容繼續儲存在原來檔案讀取的內容中,不然替換的內容不會被儲存,sub函數添加數量是因為有兩個NOUN,會把同時替換,所以設定一次只替換一個16 print(words)17 #新內容寫入新檔案18 nwfile= open(‘sentence1.txt‘,‘w‘)19 nwfile.write(words)20 nwfile.close()
Python-正則與檔案項目(瘋狂填詞)