【问题标题】:Collecting comments from Reddit, outputting to CSV file从 Reddit 收集评论,输出到 CSV 文件
【发布时间】:2020-02-20 00:06:38
【问题描述】:

我正在尝试从 Reddit 上的某个提交中抓取 cmets 并将它们输出到 CSV 文件。

import praw
import csv

reddit = praw.Reddit(client_id='ClientID', client_secret='ClientSecret', user_agent='UserAgent')

Submission = reddit.submission(id="SubmissionID")

with open('Reddit.csv', 'w') as csvfile:
    for comment in submission.comments:
        csvfile.write(comment.body)

问题在于,对于每个单元格,cmets 似乎是随机拆分的。我希望每个评论都在自己的单元格中。关于如何实现这一点的任何想法?

【问题讨论】:

  • 如果您在 csv 中添加原始 submission.comments 数据的外观以及您期望的最终结果可能会有所帮助

标签: python csv reddit praw


【解决方案1】:

您正在导入 csv 库,但实际上并未使用它。使用它,您的问题可能会消失。

https://docs.python.org/3/library/csv.html#csv.DictWriter

import csv
# ...    
comment = "this string was created from your code"
# ...
with open('names.csv', 'w', newline='') as csvfile:
    fieldnames = ['comment']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'comment': comment})

【讨论】:

    【解决方案2】:

    要在 Python 中编写 CSV 文件,请使用 the csv module,特别是 csv.writer()。您在代码的顶部导入此模块,但您从不使用它。

    在您的代码中使用它,如下所示:

    with open('Reddit.csv', 'w') as csvfile:
        comment_writer = csv.writer(csvfile)
        for comment in submission.comments:
            comment_writer.writerow([comment.body])
    

    在这里,我们使用csv.writer() 从我们打开的文件中创建一个CSV 写入器,我们称之为comment_writer。然后,对于每个评论,我们将另一行写入 CSV 文件。该行表示为一个列表。由于我们在每一行上只有一条信息要写入,因此列表只包含一项。该行是[comment.body]

    csv 模块负责确保带有换行符、逗号或其他特殊字符的值被正确格式化为 CSV 值。


    请注意,对于某些包含许多 cmets 的提交,您的 PRAW 代码可能会引发类似于 'MoreComments' object has no attribute 'body' 的异常。 PRAW docs discuss this,我鼓励您阅读它以了解更多信息,但要知道我们可以通过进一步修改我们的循环来避免在代码中发生这种情况:

    from praw.models import Comment
    
    # ...
    
    with open('Reddit.csv', 'w') as csvfile:
        comment_writer = csv.writer(csvfile)
        for comment in submission.comments:
            if isinstance(comment, Comment):
                comment_writer.writerow([comment.body])
    

    此外,您的代码只能获取提交的顶级 cmets。如果您对更多内容感兴趣,请参阅this question,这是关于如何从提交中获得不仅仅是顶级 cmets。

    【讨论】:

    • 非常感谢您全面的教学回答!我真的很感激
    【解决方案3】:

    我猜单元格不是随机拆分的,而是以逗号、空格分号拆分的。您可以使用 delimiter 参数选择要在哪个字符处分割单元格。

    import csv
    
    with open('Reddit.csv', 'w') as csvfile:
        comments = ['comment one','comment two','comment three']
        csv_writer = csv.writer(csvfile, delimiter='-')
        csv_writer.writerow(comments)
    

    【讨论】:

    • 您的代码创建了csv_writer,然后不使用它。这似乎不正确。您能否更正您的答案,使其实际使用csv_writer,以便提问者可以看到如何使用它?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 2022-11-10
    • 2019-11-04
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多