我正在使用Python,我试图找出你是否可以判断一个单词是否在字符串中。

我找到了一些关于识别单词是否在字符串中的信息-使用.find,但是否有一种方法来执行if语句。我想要这样的东西:

if string.find(word):
    print("success")

当前回答

使用regex是一种解决方案,但对于这种情况来说太复杂了。

您可以简单地将文本分割成单词列表。使用split(separator, num)方法。它返回字符串中所有单词的列表,使用分隔符作为分隔符。如果separator未指定,则对所有空格进行分割(您可以选择将分割的数量限制为num)。

list_of_words = mystring.split()
if word in list_of_words:
    print('success')

这将不工作的字符串与逗号等。例如:

mystring = "One,two and three"
# will split into ["One,two", "and", "three"]

如果你也想拆分所有的逗号等,使用分隔符参数如下:

# whitespace_chars = " \t\n\r\f" - space, tab, newline, return, formfeed
list_of_words = mystring.split( \t\n\r\f,.;!?'\"()")
if word in list_of_words:
    print('success')

其他回答

如果匹配字符序列还不够,需要匹配整个单词,这里有一个简单的函数可以完成这项工作。它基本上是在必要的地方添加空格,并在字符串中搜索空格:

def smart_find(haystack, needle):
    if haystack.startswith(needle+" "):
        return True
    if haystack.endswith(" "+needle):
        return True
    if haystack.find(" "+needle+" ") != -1:
        return True
    return False

这里假设逗号和其他标点符号已经被去掉。

出了什么问题:

if word in mystring: 
   print('success')

拆分字符串,剥离单词和标点符号怎么样?

w in [ws.strip(',.?!') for ws in p.split()]

如有需要,请注意小写或大写:

w.lower() in [ws.strip(',.?!') for ws in p.lower().split()]

也许是这样:

def wcheck(word, phrase):
    # Attention about punctuation and about split characters
    punctuation = ',.?!'
    return word.lower() in [words.strip(punctuation) for words in phrase.lower().split()]

示例:

print(wcheck('CAr', 'I own a caR.'))

我没有检查性能……

使用regex是一种解决方案,但对于这种情况来说太复杂了。

您可以简单地将文本分割成单词列表。使用split(separator, num)方法。它返回字符串中所有单词的列表,使用分隔符作为分隔符。如果separator未指定,则对所有空格进行分割(您可以选择将分割的数量限制为num)。

list_of_words = mystring.split()
if word in list_of_words:
    print('success')

这将不工作的字符串与逗号等。例如:

mystring = "One,two and three"
# will split into ["One,two", "and", "three"]

如果你也想拆分所有的逗号等,使用分隔符参数如下:

# whitespace_chars = " \t\n\r\f" - space, tab, newline, return, formfeed
list_of_words = mystring.split( \t\n\r\f,.;!?'\"()")
if word in list_of_words:
    print('success')

你可以在"word"前后加一个空格。

x = raw_input("Type your word: ")
if " word " in x:
    print("Yes")
elif " word " not in x:
    print("Nope")

这样它会查找“word”前后的空格。

>>> Type your word: Swordsmith
>>> Nope
>>> Type your word:  word 
>>> Yes