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

Using regular expressions to match a word in Python

我正在使用 PRAW 制作一个 reddit 机器人,该机器人接收说 "alot" 的人的评论作者并将他们的用户名存储到列表中。我在使用正则表达式以及如何让字符串工作时遇到了麻烦。这是我的代码。

#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 而不是 alot 作为字符串的一部分。例如 zealot。每当我 运行 这个,它不会找到我发表的评论。有什么建议吗?

您正在检查字符串操作,不是 RE 操作,在

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 将解释为 "word boundary".

可能还有其他错误,但我尽量不在每个问题中查找超过两个错误...:-)