使用正则表达式匹配Python中的单词

时间:2015-01-22 17:39:59

标签: python regex praw

我正在使用PRAW制作一个reddit机器人,该机器人的评论作者会说“#34;很多"并将其用户名存储到列表中。我正在使用正则表达式以及如何使字符串工作。这是我的代码。

#importing praw for reddit api and time to make intervals

import praw
import time
import re


username = "LewisTheRobot"
password = 



r = praw.Reddit(user_agent = "Counts people who say alot")

word_to_match = ['\balot\b']

storage = []

r.login(username, password)

def run_bot():
    subreddit = r.get_subreddit("test")
    print("Grabbing subreddit")
    comments = subreddit.get_comments(limit=200)
    print("Grabbing comments")
    for comment in comments:
        comment_text = comment.body.lower()
        isMatch = any(string in comment_text for string in word_to_match)
        if comment.id not in storage and isMatch:
            print("Match found! Storing username: " + str(comment.author) + " into list.")
            storage.append(comment.author)


    print("There are currently: " + str(len(storage)) + " people who use 'alot' instead of ' a lot'.")


while True:
    run_bot()
    time.sleep(5)

所以我正在使用的正则表达式查找单词alot而不是很多作为字符串的一部分。示例ze 很多。每当我运行它时,它都不会找到我所做的评论。有什么建议吗?

1 个答案:

答案 0 :(得分:3)

您正在检查字符串操作,

isMatch = any(string in comment_text for string in word_to_match)

这里的第一个in检查子字符串 - 与RE无关。

将此更改为

isMatch = any(re.search(string, comment_text) for string in word_to_match)

此外,初始化时出错:

word_to_match = ['\balot\b']

'\b'是代码0x08(退格)的字符。 始终对RE模式使用原始字符串语法,以避免此类陷阱:

word_to_match = [r'\balot\b']

现在你会有几个字符,反斜杠然后b,RE会将其解释为“字边界”。

可能还有其他错误,但我不会在每个问题上寻找超过两个错误......: - )