楼主: lobster_future
1065 4

[程序分享] 新手求助,没什么论坛币希望大家路过看看,学python不到一周自己太弱鸡 [推广有奖]

  • 1关注
  • 0粉丝

已卖:1份资源

本科生

84%

还不是VIP/贵宾

-

威望
0
论坛币
96 个
通用积分
0
学术水平
0 点
热心指数
1 点
信用等级
5 点
经验
803 点
帖子
131
精华
0
在线时间
24 小时
注册时间
2017-1-15
最后登录
2018-4-13

楼主
lobster_future 发表于 2017-6-9 15:40:56 |AI写论文
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里面这样转成字符串。
关键词:python 新手求助 论坛币 没什么 substitute

沙发
shell800 发表于 2017-6-9 15:40:57
或者转换一下。str(content)  findall里面这样转成字符串。

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

板凳
shell800 发表于 2017-6-12 16:03:32
readlines改为read。

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

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群
GMT+8, 2026-2-8 01:14