2024-05-16 23:42:24 发布
网友
假设我在找单词"or"。我要检查这个词是作为一个词还是另一个词的子串出现的。在
"or"
例如
Input - "or" Output - "true"Input - "for" Output - "false"
Input - "or" Output - "true"
Input - "for" Output - "false"
我想我可以检查一下前后的字符是否是字母,但是有没有更有效/更简单的方法?谢谢
编辑 此外,字符串将是句子的一部分。所以我希望“我能不能去购物”返回true,而“我可以去买鞋”返回false。 因此使用==是行不通的。对不起,我应该早点提这个
可以使用正则表达式执行以下操作:
import re def contains_word(text, word): return bool(re.search(r'\b' + re.escape(word) + r'\b', text)) print(contains_word('or', 'or')) # True print(contains_word('for', 'or')) # False print(contains_word('to be or not to be', 'or')) # True
如果一个测试位于行中,则创建一个只包含一个测试的checker
def check_word_in_line(word, line): return " {} ".format(word) in line print(check_word_in_line("or", "I can go shopping or not")) //True print(check_word_in_line("or", "I can go shopping for shoes")) //False
使用正则表达式。在
>>> import re >>> re.search(r'\bor\b', 'or') <_sre.SRE_Match object at 0x7f445333a5e0> >>> re.search(r'\bor\b', 'for') >>>
可以使用正则表达式执行以下操作:
如果一个测试位于行中,则创建一个只包含一个测试的checker
使用正则表达式。在
相关问题 更多 >
编程相关推荐