【发布时间】:2013-10-29 08:22:04
【问题描述】:
我试图做的是遍历一个 cmets 列表,删除已添加到名为 cText 的值的当前注释,如果 cText 超过 9000 个字符,则对同一函数进行递归调用并将其返回值添加到botComments。我还尝试将返回的botComments 列表从递归函数合并到最上面的botComments 列表和botComments + repliesToComments(comments, author),尽管我不知道我是否做对了。奇怪的是,它似乎也无法在列表中找到肯定有评论抛出我在下面粘贴的异常的评论。在我的 AP Comp-Sci 课程中,我的递归很糟糕,尽管我希望从任何可以修复我下面的代码的人那里了解我做错了什么。谢谢:)
这是我目前的例外情况:
Traceback (most recent call last):
File "C:\Users\Josh\Desktop\bot.py", line 62, in <module>
print(repliesToComments(submission.comments, submission.author.name))
File "C:\Users\Josh\Desktop\bot.py", line 36, in repliesToComments
botComments + repliesToComments(comments, author)
File "C:\Users\Josh\Desktop\bot.py", line 39, in repliesToComments
comments.remove(comment)
ValueError: list.remove(x): x not in list
这是我的代码:
def repliesToComments(comments, author):
botComments = []
multiReplies = False
cText = "Here is a list of all the comments /u/" + author + ''' has submitted to top-level comments:
***
Original Comment | /u/''' + author + ''''s Reply
---------|---------
'''
for comment in comments[:]:
if (hasattr(comment, "replies")):
for comment2 in comment.replies:
if (hasattr(comment2, "author") and comment2.author.name == author):
oCommentLink = "[" + comment.body.replace("\n", "")[:50] + "](" + submission.permalink + "" + comment2.parent_id.replace("t1_", "") + ")..."
rCommentLink = "[" + comment2.body.replace("\n", "")[:50] + "](" + submission.permalink + "" + comment2.name.replace("t1_", "") + ")..."
if (len(cText) + len(oCommentLink + " | " + rCommentLink + "\n") > 9000): #Stop here to make sure we don't go over 10000 char limit!
multiReplies = True
cText += '''
***
[FAQ](http://pastebin.com/raw.php?i=wUGmE8X5) | Generated at ''' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " PST" + " | *This comment only shows a partial amount of OPs total replies due to character limit. The rest are shown in a reply to this comment.*"
botComments.append(cText)
botComments + repliesToComments(comments, author)
break
cText += oCommentLink + " | " + rCommentLink + "\n"
comments.remove(comment)
if (multiReplies == False):
cText += '''
***
[FAQ](http://pastebin.com/raw.php?i=wUGmE8X5) | Generated at ''' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " PST"
botComments.append(cText)
return botComments
【问题讨论】:
标签: python for-loop recursion python-3.x reddit