• Python实践练习:疯狂填词


    题目

    创建一个疯狂填词(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.
    

    结果应该打印到屏幕上,并保存为一个新的文本文件。

    代码

    #! python3
    # 创建一个疯狂填词(Mad Libs)程序,它将读入文本文件,并让用户在该文本文件中出现 ADJECTIVE、NOUN、ADVERB 或 VERB 等单词的地方,加上他们自己的文本。
    
    import os, re
    
    txtFile = r'D:CodeVimCodePython_auto8_疯狂填词_r.txt'
    saveFile = r'D:CodeVimCodePython_auto8_疯狂填词_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 + ' 单词: 
    ')
        regexWord = re.compile(toReplItem)
        strTxt = regexWord.sub(replWord, strTxt)
    
    replFileOpen = open(saveFile, 'w')
    replFileOpen.write(strTxt)
    replFileOpen.close()
    print(strTxt + '
    已经写入8_疯狂填词_w.txt
    ')
    
  • 相关阅读:
    Character Encoding题解(容斥)
    P1445 [Violet]樱花 题解(推式子)
    F. Stone 题解(对称博弈)
    M. 810975 题解(容斥)
    P1365 WJMZBMR打osu! / Easy 题解(期望dp)
    icpc济南
    C#创建windows服务并定时执行
    批处理 windows 服务的安装与卸载
    前台单击文件,jQuery删除后台相应真实的文件
    Jquery直接调用后台方法(WebMethod框架的使用)
  • 原文地址:https://www.cnblogs.com/wudongwei/p/9013626.html
Copyright © 2020-2023  润新知