首页 > 解决方案 > 使用正则表达式的 Python 的 Mad Libs ATBS

问题描述

我正在研究 ATBS 的“Mad Libs”项目。程序应该读入文本文件,并允许用户在文本文件中出现“ADJECTIVE”、“NOUN”、“ADVERB”或“VERB”的任何地方添加自己的文本。

我到目前为止的代码如下:

    import os, re

    NewFile=input('Please enter the path of the file to be used:')
    NewFilepath=os.path.abspath(NewFile)
    print(NewFilepath)
    if os.path.exists(NewFilepath)==True: 
        open(NewFile, 'a')
    else: 
        print('This file does not exist. Creating a new file.')
        open(NewFile, 'w')

    NewFileContent=NewFile.read()

    def NewMadLibs(): 
        SpeechParts=re.compile(r'ADJECTIVE|NOUN|ADVERB|VERB', re.I)
        match=re.findall(NewFileContent)
        for match in NewFileContent: 
            if match=='ADJECTIVE': 
                adjective=input('Enter an adjective:\n')
            SpeechParts.sub(adjective, 'ADJECTIVE')
            if match=='NOUN': 
                noun=input('Enter a noun:\n')
            SpeechParts.sub(noun, 'NOUN')
            if match=='ADVERB': 
                adverb=input('Enter an adverb:\n')
            SpeechParts.sub(adverb, 'ADVERB')
            if match=='VERB': 
                verb=input('Enter a verb:\n')
            SpeechParts.sub(verb, 'VERB')

    NewMadLibs(NewFileContent)
    UserMadLibsFile=NewFileContent.read()
    print(UserMadLibsFile)
    new_FileName='new_'+'source.txt'
    new_file=open(new_FileName, 'w')
    new_file.write(UserMadLibsFile)
    new_file.close()
    print("The file is saved as 'new_source.txt'")

出现的错误消息如下所示:

    Traceback (most recent call last):
    File "/Users/myname/Documents/MadLibsNewTry.py", line 16, in <module>
    NewFileContent=NewFile.read()
    AttributeError: 'str' object has no attribute 'read'

我对这个错误感到困惑,因为我以附加模式或写入模式打开 NewFile,具体取决于文件(路径)是否已经存在。那不应该创建或打开“NewFile”并且它将是一个文件对象,而不是一个字符串?代码没有达到这一点,但我认为在最后一个块中会出现类似的错误:UserMadLibsFile=NewFileContent.read()。

对于这个练习问题我应该考虑的任何建议或其他方法,我都持开放态度。

标签: pythonpython-3.x

解决方案


推荐阅读