Python程式設計快速上手 實踐專案8 9 2

2021-08-13 10:28:14 字數 1321 閱讀 2606

8.9.2 瘋狂填詞

建立乙個瘋狂填詞(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.

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

用spilt()方法處理不了標點,考慮用正規表示式直接搜尋出需要替換的關鍵字,然後用re.sub()的方法替換。

原文中出現了兩次「noun」,用sub方法替換的時候,會將兩個地方一起替換了,後面查閱了文件才知道sub方法最後可以加乙個count引數可以控制每次替換的個數。

import re

#讀取文字

file = open('test.txt', 'r')

words = file.read()

file.close()

#查詢關鍵字

pattern = re.compile('adjective|noun|verb|adverb')

mo = pattern.findall(words)

#依次替換每乙個關鍵字

for word in mo:

repl = input(f'enter a :\n> ')

regex = re.compile(word)

words = regex.sub(repl, words, 1)

print(words)

#替換後的文字寫入新的檔案

new_file = open('test2.txt', 'w')

new_file.write(words)

new_file.close()

Python程式設計快速上手 實踐專案

例如,字典值 意味著玩家有1條繩索 6個火把 42枚金幣等。寫乙個名為displayinventory 的函式,它接受任何可能的物品清單,並顯示如下 inventory 12 arrow 42 gold coin 1 rope 6 torch 1 dagger total number of ite...

python程式設計快速上手 實踐專案 9 8 1答案

import shutil,os defcopytofolder tfolder,ofolder,filetype 獲取待複製資料夾的目錄名稱長度 nnn len os.path.dirname tfolder 遍歷目錄樹 for foldername,subfolders,filenames in...

python程式設計快速上手 實踐專案答案5

字典值 寫乙個名為displayinventory 的函式,它接受任何可能的物品清單,並顯示如下 inventory 1 rope 6 torch 42 gold coin 1 dagger 12 arrow total number of items 62 如下 stuff defdisplayi...