我试图做的是遍历评论列表,删除已添加到名为 的值的当前评论,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