gpt4 book ai didi

Python:正则表达式单词匹配

转载 作者:太空宇宙 更新时间:2023-11-04 01:00:23 26 4
gpt4 key购买 nike

我写了这个小脚本,但我无法让 re.search 函数正常工作。我试图只匹配确切的词(笑话),但 elif 语句一直返回打印,因为它在句子变量中找到了笑话(来自 clown )。有什么方法可以让它计算笑话这个词中的字母数量,所以只有当笑话是一个独立的词时它才正确?

#!/usr/bin/python
import re

sentence = 'The substantial treat shouts with the jokers'
find_emergency = re.search( r'emergency', sentence, re.M|re.I)
find_joke = re.search( r'joke', sentence, re.M|re.I)

if find_emergency :
print 'Do you want to set this email as urgent?'
elif find_joke :
print "Do you want to mark this email as non-urgent?"
else :
print "Sorry, we couldn\'t find what you were looking for ;("

最佳答案

find_joke = re.search( r'\bjoke\b', sentence, re.M|re.I)

为此使用 \bword boundary

关于Python:正则表达式单词匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33095657/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com