全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 python论坛
1018 4
2017-06-09
悬赏 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()

最佳答案

shell800 查看完整内容

或者转换一下。str(content) findall里面这样转成字符串。
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2017-6-9 15:40:57
或者转换一下。str(content)  findall里面这样转成字符串。
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2017-6-12 15:59:45
content=mad.readlines()  改为 content=mad.read()
readlines()返回的是列表,findall接受的参数是字符串。
楼主能不能先给一两分我下载个文件。
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2017-6-12 16:03:32
readlines改为read。
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2017-6-12 16:06:17
回复不知道为什么被审核。不敢写多。
findall接受的参数是字符串。readlines返回的是列表。
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

分享

扫码加好友,拉您进群