检查字符串是否显示为自己的单词 - Python

时间:2017-12-11 18:08:30

标签: python string python-3.x

让我们说我正在寻找"or"这个词。我想要的是检查该单词是单词还是另一个单词的子串。

E.g。

  

输入 - "或"   输出 - " true"

     

输入 - "用于"   输出 - " false"

我想我可以检查之前和之后的字符是否是字母,但有更有效/更简单的方法吗?感谢

修改 另外,字符串将是句子的一部分。所以我想"我可以去购物或不去购物#34;回归真实,但"我可以去购买鞋子"返回false。 因此使用==不会起作用。对不起,我之前应该提到这个

4 个答案:

答案 0 :(得分:4)

使用正则表达式。

>>> import re
>>> re.search(r'\bor\b', 'or')
<_sre.SRE_Match object at 0x7f445333a5e0>
>>> re.search(r'\bor\b', 'for')
>>> 

答案 1 :(得分:1)

您可以使用正则表达式:

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

答案 2 :(得分:1)

如果

,则仅使用测试创建一个检查器
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

答案 3 :(得分:0)

您可以使用nltk(自然语言工具包)将句子拆分为单词,然后检查==是否存在某个单词。

NLTK Installation

NLTK Package Download

import nltk

def checkword(sentence):
    words = nltk.word_tokenize(sentence)
    return any((True for word in words if word == "or"))

print(checkword("Should be false for."))
print(checkword("Should be true or."))