Python:将文件中的数据加载到 IRC 机器人中
我正在尝试从文件加载正则表达式模式列表,并且希望它将每个正则表达式条目拉入一个数组,该数组稍后可用于匹配传入的文本模式,然后根据它们触发操作。
我已经掌握了使 re.search() 工作的窍门,但是如何从文件加载正则表达式模式,然后使用 re.search() 参数扫描从文件中提取的各种正则表达式模式?
I'm trying to load a list of regex patterns from a file, and I'd like it to pull each regex entry into an array which can later be used to match incoming text patterns, then trigger an action based on them.
I've already gotten the hang of making re.search() work, but how can I load the regex patterns from a file, then subsequently scan the various regex patterns pulled from the file with the re.search() argument?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想在正则表达式与文本模式匹配时触发操作,则可能需要将正则表达式映射到该操作(假设它是对与映射在同一文件中定义的函数的引用)。假设我们在 python 文件
rules.py
中定义规则,如下所示:在
main.py
中导入映射,编译所有正则表达式(一次性操作以避免每次搜索都重新编译它们),然后对传入的消息进行搜索。当然,这取决于您想要如何触发该操作,但我希望主要原则是明确的。
If you want to trigger an action when a regex matches an text pattern, you probably need some mapping of regex to the action (let's assume it is a reference to a function defined in the same file as the mappings). Say we define the rules in a python file
rules.py
like this:In your
main.py
you import the mappings, compile all regex expressions (one-time operation to avoid recompiling them every search) and then do a search against incoming messages.Of course it depends on how you want to trigger that action, but I hope the main principle is clear.