悬赏 15 个论坛币 已解决
新手求助
任务要求 打开一个文本 将所有含有 ADJECTIVE, NOUN, ADVERB OR VERB的地方,请用户输入一个ADJECTIVE, NOUN, ADVERB OR VERB,并填充文本,并且将由用户改过的文本输出并保存到一个新的文本
现在代码跑完之后 总是在加粗地点有点问题 请大家指教
并出现这样的字样
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\madLibs.py", line 23, in <module>
typeRegex.sub(r'%s'%(temp),copytext)
TypeError: expected string or bytes-like object
#!python3
#madLibs - to attempt the user to type in adjective, noun, adverb and
#verb to replace the ADJECTIVE, NOUN, ADVERB OR VERB
import os,re,pyperclip
##open the text
#suppose there is a text named madLibs.txt
mad=open('madLibs.txt','r')
content=mad.readlines()
print(content)
copytext=content
##find whether these specific words exist or not
typeRegex=re.compile(r'ADJECTIVE|ADVERB|NOUN|VERB',re.I)
##We need to run the loop through every sentence of the text
for i in range(len(content)):
for j in range(len(typeRegex.findall(content))):
##we want to get every word that we need to substitute
##in this for loop, maybe we should consider that j has always changed
print('Enter an %s:'%(str(typeRegex.findall(content)[j])).lower())
temp=str(input())
##substitute with the word that user input
typeRegex.sub(r'%s'%(temp),copytext)
##print(typeRegex.findall(content))
##Now we get a list of sentences with the words substituting to the input of user
madLibsNew=open('madLibsNew','w')
madLibsNew.write('This is the new text that some adjectives,adverbs, verbs and nouns that has been substitute from madLabs.txt')
madLibsNew.close()
for i in range(len(copytext)):
madLibsNew=open('madLibsNew','a')
madLibsNew.write(copytext)
madLibsNew.close()