1. 程式人生 > >Python-正則與文件項目(瘋狂填詞)

Python-正則與文件項目(瘋狂填詞)

sub utf-8 pan In 例如 then fin HA 創建

創建一個瘋狂填詞(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-正則與文件項目(瘋狂填詞)