Practical Python Exercise: Crazy Words

topic

Create a Mad Libs program that will read in a text file and let users add their own text where words like ADJECTIVE, NOUN, ADVERB, or VERB appear in the text file.
For example, a text file might look like this:

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

The program will find these occurrences and prompt the user to replace them.

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

The following text files will be created:

The silly panda walked to the chandelier and then screamed. A nearby pickup
truck was unaffected by these events.

The results should be printed to the screen and saved as a new text file.

code

#! python3
# 创建一个疯狂填词(Mad Libs)程序,它将读入文本文件,并让用户在该文本文件中出现 ADJECTIVE、NOUN、ADVERB 或 VERB 等单词的地方,加上他们自己的文本。

import os, re

txtFile = r'D:\Code\VimCode\Python_auto\8_疯狂填词_r.txt'
saveFile = r'D:\Code\VimCode\Python_auto\8_疯狂填词_w.txt'

if os.path.isfile(txtFile):
    txtFileOpen = open(txtFile,'r')
    strTxt = txtFileOpen.read()
    txtFileOpen.close()
else:
    print(txtFile + "不存在,退出!")
    exit(1)

# 对特定单词进行替换
toReplList = ['ADJECTIVE', 'NOUN', 'ADVERB', 'VERB']
for toReplItem in toReplList:
    replWord = input("输入你要替换的 " + toReplItem + ' 单词: \n')
    regexWord = re.compile(toReplItem)
    strTxt = regexWord.sub(replWord, strTxt)

replFileOpen = open(saveFile, 'w')
replFileOpen.write(strTxt)
replFileOpen.close()
print(strTxt + '\n已经写入8_疯狂填词_w.txt\n')

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326093743&siteId=291194637