忽略区分大小写的关键字集

时间:2018-07-23 22:46:48

标签: python api reddit praw

在使用PRAW搜索特定子书签上的关键字时,我试图忽略大小写。

$es

def run_bot(r, comments_replied_to): print "Obtaining 25 comments..." keywords = {"eyebleach", "eye bleach", "enough internet for today", "enough internet for the day"} for comment in r.subreddit('test').comments(limit=25): for keyword in keywords: if keyword.lower() in comment.body and comment.id not in comments_replied_to and comment.author != r.user.me(): print "Keyword found in comment " + comment.id + "!" posts = r.subreddit('eyebleach').random() print("Generated random image post from /r/eyebleach: " + posts.url) comment_reply = "[**Need some eye bleach?**](%s)" % posts.url comment_reply += "\n\n/u/eyebleacher_bot was created by [@cjgetty](http://github.com/cjgetty).\n\nThis eye bleach has been randomly generated from [/r/eyebleach](http://reddit.com/r/eyebleach)." comment.reply(comment_reply) print "Replied to comment " + comment.id + "!" comments_replied_to.append(comment.id) with open ("comments_replied_to.txt", "a") as f: f.write(comment.id + "\n") print "Sleeping for 10 seconds..." #Sleep for 10 seconds... time.sleep(10) 集中,无论如何(低,高,混合),我将如何搜索那些相同的关键字?

2 个答案:

答案 0 :(得分:0)

使用str.lower()方法,您可以不区分大小写地比较两个字符串。例如

a = 'sTriNg LoWeR'
b = 'string lower'
c = 'STRING LOWER'

if(a.lower() == b.lower() == c.lower()):
    print('All equal!')

打印All equal!

答案 1 :(得分:0)

if keyword.lower() in comment.body and comment.id not in comments_replied_to and comment.author != r.user.me():

if keyword.lower() in comment.body.lower() and comment.id not in comments_replied_to and comment.author != r.user.me():

您在if语句的 comment.body 中添加 .lower()