python - 使用正则表达式的 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()。
对于这个练习问题我应该考虑的任何建议或其他方法,我都持开放态度。
解决方案
推荐阅读
- haskell - 来自 Simon Marlow 的《Haskell 中的并行和并发编程》一书中的严格评估示例
- java - brokerURL 语法我不清楚
- node.js - 使用相同输入时的 Node.js 运行时变化
- javascript - 接受通用参数和字符串数组的打字稿函数
- tensorflow - InvalidArgumentError:找到 2 个根错误。(0) 无效参数:矩阵大小不兼容:In[0]:[665,64],In[1]:[42560,1]
- javascript - 为什么当我改变轴(x,y)的位置时,我的图形会像下图一样改变形状?
- reactjs - 类型“模型”上不存在属性“登录”
- python - 如何计算用于股票预测的 LSTM 神经网络的准确性?
- spring-social - Spring OAuth2 将原始请求保存在会话中并重定向到原始 URL
- python - 使用 pie char 和 bar char pandas 的子图