iamthewalrus iamthewalrus - 10 months ago 33
Python Question

How to match a sentence exactly, rather than substring match (Solved)

So I created a simple reddit bot using PRAW:

import praw
import time
from praw.helpers import comment_stream

r = praw.Reddit("han_solo_response")

target_text = "I love you"
response_text = "I know"

processed = []
while True:
for c in comment_stream(r, 'all'):
if target_text in c.body and c.id not in processed:
#if find comment not in cache
processed.append(c.id) #then push the response

It generates the han solo response " i know" every time someone anywhere on reddit posts " i love you" per the famous star wars movie exchange. It is working now but it is catching anything containing "i love you" eg i had to delete one comment where the guy was saying " i love your car".

How can I limit its trigger to precisely "I love you", not "your" or any other word containing "you", or for that matter, make it so that the response is only triggered by the standalone phrase, not when it appears within the context of a sentence.


This line:

if target_text in c.body and c.id not in processed:

should be:

if target_text == c.body and c.id not in processed:

If you want to make it case-insensitive:

target_text = "i love you"


if target_text == c.body.lower() and c.id not in processed: