Search code examples
pythonreddit

Searching for reddit comment containing any word from list PSAW python


Hi I'm using PSAW and PRAW to fetch reddit comments.

Here is the search code:

gen = api.search_comments(subreddit="subreddit1, subreddit2", q="word1, word2")

This code checks for comments in subreddit1 and 2 but looks for comments with both word1 and word2. How can i make it so that it searches for comments that contain word1 or word2 or both?

Thanks (let me know if you need any more information)


Solution

  • The short answer is that you cannot do what you're asking in one step, at least not as far as I have seen. But you can certainly do it in multiple steps.

    # to search for either word1 or word 2, use |
    gen1 = api.search_comments(subreddit="subreddit1, subreddit2", q="word1|word2")
    
    # to search for both word1 and word 2, use &
    gen2 = api.search_comments(subreddit="subreddit1, subreddit2", q="word1&word2")
    

    FYI - Searching for comments in PSAW is essentially a wrapper around

    api.pushshift.io/reddit/comment/search?q=...
    

    and for your question you can play around with that website to get a better understanding of what it will return. The API isnt perfect, you'll still get some comments that contain both words even if you used |, and you'll still get some comments that only contain one of the words even if you used &, but those operators take the bulk of the work off your shoulders.