Python-正則與檔案項目(瘋狂填詞)

來源:互聯網
上載者:User

標籤: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-正則與檔案項目(瘋狂填詞)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.