python praw 获取评论并以文件格式写入

python praw get comment and write in file format

我正在获取 subreddit 的内容。 subreddit 是 AR。 我需要获取post ID、标题、post内容、作者、post日期、分数、评论和评论ID,然后写入txt文件。 我现在面临的问题是:

(1)我可以将评论和评论ID合并到一个文件中吗?因此,它将是 post ID, title, post content, author, post date, score, comments, and comment ID (2) 我得到的 selftext 有断线,所以在我的 output.txt 中显示为

blablabla

blablabla

blablabla

例如,[this reddit][1] 有多个分界线。 我希望所有内容都在一行中,因为数据将被传输到 csv/excel 以供将来分析。

我的代码:

import praw, datetime, os
reddit = praw.Reddit('bot1')
subreddit = reddit.subreddit('AR')
for submission in subreddit.top(limit=1):
    date = datetime.datetime.utcfromtimestamp(submission.created_utc)

    for comment in submission.comments:
        print("Comment author: ", comment.author)
        print("Comments: ", comment.body)
        indexFile_comment = open('path' + 'index_comments.txt', 'a+')
        indexFile_comment.write('"' + str(comment.author) + '"' + ', ' + '"' + str(comment.body) + '"' + '\n')
    print("Post ID: ", submission.id)
    print("Title: ", submission.title)
    print("Post Content: ", submission.selftext)
    print("User Name: ", submission.author)
    print("Post Date: ", date)
    print("Point: ", submission.score)
    indexFile = open('path' + 'index.txt', 'a+')
    indexFile.write('"' + str(submission.id) + '"' + ', ' + '"' + str(submission.title) + '"' + ', ' + '"' + str(submission.selftext) + '"' + ', ' + '"' + str(submission.author) + '"' + ', ' + '"' + str(date) + '"' + ', ' + '"' + str(submission.score) + '"' + '\n')
    print ("Successfuly writing in file")
    indexFile.close()

要在一行中完成提交,您可以在代码中实现 st.replace("\n"," ")。其中变量 stsubmission.selftext

要获取评论 ID,您可以 comment.id 并在您的 for 循环中获取正文 comment.body

编辑:

在第一行中,我只添加了submission.idsubmission.title,但您可以按照相同的方式添加其余部分。该循环将注释添加到同一字符串的末尾。在 for 循环之后,我用 space 字符替换任何换行符。您可以将 record 写入文本文件,当您转到下一次提交时,将下一个 record 附加到文本文件中的新行。

record = str(submission.id) + " " + str(submission.title) + " " 
for comment in submission.comments:
    record = record + comment.author + " " + comment.body + " "
record.replace("\n", " ")