2

我在stackoverflow上做了一些研究,但找不到任何东西……也许是因为我真的不知道要找什么。我编写了一个脚本来将 reddit 评论(来自其中一个提交)添加到 wordpress。一切都很好,没有任何问题......但是循环中有一个奇怪的行为,我完全不明白。让我们从示例代码开始(它是名为“generuj”的函数的一部分):

komment = WordPressComment()
mySubmissionId = submission.id
komentarze = r.get_submission(submission_id=mySubmissionId)
komentarze.replace_more_comments(limit=0, threshold=1)
flat_comments = praw.helpers.flatten_tree(komentarze.comments)

上面的代码无关紧要,但我把它放在这里是为了更好地理解每次提交都有不同数量的评论,但不超过 200 .. 所以有时很少有 5 条,有时 184 条它们存储在 flat_comments 中

    listaKomentarzy = []
    for comment in flat_comments:
        if (str(comment.body).__len__() > 20 and str(comment.body).__len__() < 50 and not 'sometestword' in str(comment.body)):
        try:
            listaKomentarzy.append(str(comment.body))

        except:
            e = sys.exc_info()[0]
            print e

        else:
            print (Fore.RED + Style.DIM + "wrong comment")


print len(listaKomentarzy) #to be sure that all comments are in listaKomentarzy

longKom = max(listaKomentarzy, key=len)
indeks = listaKomentarzy.index(longKom)
del listaKomentarzy[indeks]

在这里,我删除了最长的评论并且它有效......所以此时一切仍然或至少看起来工作正常。然而噩梦从这里开始:

for row in listaKomentarzy:
    komment.content = row
    print row

上面的代码是名为generuj的函数的一部分,它也在for循环中运行,该循环遍历每次提交(然后每次运行都会获得新的评论)以简化此代码运行函数:

generuj()
del listaKomentarzy

我使用 del listaKomentarzy 来确保每次循环开始时它都是空的,所以我的问题如下:

for row in listaKomentarzy:
    komment.content = row
    print row

脚本正在运行,一切正常......脚本正在打印每条评论(打印行),因为它应该是......但有时它不会。评论一定有什么奇怪的地方,有列表什么的,我不知道究竟是什么..我的第一个想法是python列表中可以存储多少评论是有限制的,但我发现可能有很多比我在 listaKomentarzy 中存储的要多(最多大约 200 个)。

我不知道我打破 for 循环的原因是什么。唯一改变的是评论。为了更好地解释它,我将向您展示示例。假设有 5 条投稿,第一个有 10 条评论,第二条有 20 条评论,第三条有 30 条评论,第四条有 40 条评论,第五条有 50 条评论,

我运行一个脚本,它从 submit1 加载 10 条评论并打印:comment1、comment2、comment3...comment10 然后代码确实清除 listaKomentarzy 中的评论列表,并加载 20 条评论并打印:comment1、comment2、comment3... .comment20 然后代码会清除并加载 30 条评论以进行提交 3,然后什么也没有发生(它甚至不打印一条评论)打破循环并加载 40 条评论的提交 4 并毫无问题地打印所有 40 条评论然后它加载 50 条评论的提交 5 和不打印就中断

(没有错误,服务器日志中没有信息)我不知道从哪里开始使用这段代码......有人可以帮忙吗?

4

1 回答 1

0

我找到了答案,编码存在问题,但与我认为的完全不同的地方

我不得不改变

str(comment.body).__len__()

到 str(comment.body.encode('ascii', 'ignore'))。()

于 2016-01-11T19:03:04.267 回答