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

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

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

当前回答

解决方案之一是在测试单词的开头和结尾放置一个空格。如果单词位于句首或句尾,或在任何标点符号旁边,则不适用。我的解决方案是编写一个函数,用空格替换测试字符串中的任何标点符号,并在开头和结尾或测试字符串和测试单词之间添加一个空格,然后返回出现的次数。这是一个简单的解决方案,不需要任何复杂的正则表达式。

def countWords(word, sentence):
    testWord = ' ' + word.lower() + ' '
    testSentence = ' '

    for char in sentence:
        if char.isalpha():
            testSentence = testSentence + char.lower()
        else:
            testSentence = testSentence + ' '

    testSentence = testSentence + ' '

    return testSentence.count(testWord)

计算一个单词在字符串中出现的次数:

sentence = "A Frenchman ate an apple"
print(countWords('a', sentence))

返回1

sentence = "Is Oporto a 'port' in Portugal?"
print(countWords('port', sentence))

返回1

使用'if'中的函数来测试单词是否存在于字符串中

其他回答

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

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

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

这个小函数比较给定文本中的所有搜索词。如果在文本中找到所有搜索词,则返回搜索长度,否则返回False。

也支持unicode字符串搜索。

def find_words(text, search):
    """Find exact words"""
    dText   = text.split()
    dSearch = search.split()

    found_word = 0

    for text_word in dText:
        for search_word in dSearch:
            if search_word == text_word:
                found_word += 1

    if found_word == len(dSearch):
        return lenSearch
    else:
        return False

用法:

find_words('çelik güray ankara', 'güray ankara')
if 'seek' in 'those who seek shall find':
    print('Success!')

但请记住,这匹配的是一个字符序列,而不一定是一个完整的单词——例如,'swordsmith'中的'word'是True。如果你只想匹配整个单词,你应该使用正则表达式:

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> <match object>
findWholeWord('word')('swordsmith')                   # -> None

Find返回一个整数,表示搜索项所在位置的索引。如果没有找到,则返回-1。

haystack = 'asdf'

haystack.find('a') # result: 0
haystack.find('s') # result: 1
haystack.find('g') # result: -1

if haystack.find(needle) >= 0:
  print('Needle found.')
else:
  print('Needle not found.')

我相信这个答案更接近最初的问题:在字符串中查找子字符串,但只有在整个单词?

它使用了一个简单的正则表达式:

import re

if re.search(r"\b" + re.escape(word) + r"\b", string):
  print('success')