Python - 检查Word是否在字符串中

The*_*Woo 159 python string

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

我找到了一些关于识别单词是否在字符串中的信息 - 使用.find,但有没有办法做IF语句.我希望得到以下内容:

if string.find(word):
    print 'success'
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

fab*_*ioM 321

出什么问题了:

if word in mystring: 
   print 'success'
Run Code Online (Sandbox Code Playgroud)

  • 同样谨慎一点,如果你有一个字符串"副伤寒是坏的"而你做了一个如果"伤寒"中的"副伤寒是坏的"你会得到一个真实的. (88认同)
  • 这是如何被接受的答案?它只是检查字符串中是否出现字符序列(而不是单词) (8认同)
  • @ user2567857,正则表达式 - 见Hugh Bothwell的回答. (4认同)
  • if(mystring中的word1和mystring中的word2) (4认同)
  • 有谁知道如何克服这个问题? (2认同)

Hug*_*ell 152

if 'seek' in 'those who seek shall find':
    print('Success!')
Run Code Online (Sandbox Code Playgroud)

但请记住,这匹配一系列字符,不一定是整个单词 - 例如,'word' in 'swordsmith'是真的.如果你只想匹配整个单词,你应该使用正则表达式:

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
Run Code Online (Sandbox Code Playgroud)

  • 是否有一种真正快速的方法来搜索多个单词(例如一组数千个单词),而不必构造遍历每个单词的for循环?我有一百万个句子,还有一百万个搜索词,以查看哪个句子具有哪个匹配词。目前,我要花几天的时间来处理,我想知道是否有更快的方法。 (2认同)

use*_*783 39

如果您想知道整个单词是否在以空格分隔的单词列表中,只需使用:

def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
Run Code Online (Sandbox Code Playgroud)

这种优雅的方法也是最快的.与Hugh Bothwell和daSong的方法相比:

>python -m timeit -s "def contains_word(s, w): return (' ' + w + ' ') in (' ' + s + ' ')" "contains_word('the quick brown fox', 'brown')"
1000000 loops, best of 3: 0.351 usec per loop

>python -m timeit -s "import re" -s "def contains_word(s, w): return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search(s)" "contains_word('the quick brown fox', 'brown')"
100000 loops, best of 3: 2.38 usec per loop

>python -m timeit -s "def contains_word(s, w): return s.startswith(w + ' ') or s.endswith(' ' + w) or s.find(' ' + w + ' ') != -1" "contains_word('the quick brown fox', 'brown')"
1000000 loops, best of 3: 1.13 usec per loop
Run Code Online (Sandbox Code Playgroud)

编辑: Python 3.6+的这个想法略有变化,同样快:

def contains_word(s, w):
    return f' {w} ' in f' {s} '
Run Code Online (Sandbox Code Playgroud)

  • 这是我最喜欢的答案:) (3认同)
  • 这有几个问题:(1)最后的单词(2)开头的单词(3)介于两者之间的单词,如`contains_word("说","西蒙说:不要使用这个答案") (3认同)
  • @JeffHeaton 再次,正如作者明确指出的那样,此方法专门用于“如果您想查明整个单词是否位于以空格分隔的单词列表中”。 (2认同)

Mat*_*ell 14

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.'
Run Code Online (Sandbox Code Playgroud)


Gur*_*lik 9

这个小函数比较给定文本中的所有搜索词.如果在文本中找到所有搜索词,则返回搜索长度或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
Run Code Online (Sandbox Code Playgroud)

用法:

find_words('çelik güray ankara', 'güray ankara')
Run Code Online (Sandbox Code Playgroud)


Cor*_*vax 9

您可以将字符串拆分为单词并检查结果列表.

if word in string.split():
    print 'success'
Run Code Online (Sandbox Code Playgroud)

  • 请使用[编辑]链接解释此代码的工作原理,而不仅仅是提供代码,因为解释更有可能帮助未来的读者. (3认同)
  • 这应该是匹配整个单词的实际答案。 (2认同)

daS*_*ong 8

如果匹配一系列字符是不够的,你需要匹配整个单词,这里有一个简单的函数可以完成工作.它基本上在必要时附加空格并在字符串中搜索它:

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
Run Code Online (Sandbox Code Playgroud)

这假设已经删除了逗号和其他标点符号.


tst*_*pko 8

使用正则表达式是一种解决方案,但对于这种情况来说太复杂了。

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

list_of_words = mystring.split()
if word in list_of_words:
    print 'success'
Run Code Online (Sandbox Code Playgroud)

这不适用于带逗号等的字符串。例如:

mystring = "One,two and three"
# will split into ["One,two", "and", "three"]
Run Code Online (Sandbox Code Playgroud)

如果您还想拆分所有逗号等,请使用分隔符参数,如下所示:

# 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'
Run Code Online (Sandbox Code Playgroud)


Ram*_*eez 5

检查确切单词的高级方法,我们需要在长字符串中查找:

import re
text = "This text was of edited by Rock"
#try this string also
#text = "This text was officially edited by Rock" 
for m in re.finditer(r"\bof\b", text):
    if m.group(0):
        print "Present"
    else:
        print "Absent"
Run Code Online (Sandbox Code Playgroud)


Mar*_*oma 5

当您要求一个单词而不是一个字符串时,我想提出一个对前缀/后缀不敏感并忽略大小写的解决方案:

#!/usr/bin/env python

import re


def is_word_in_text(word, text):
    """
    Check if a word is in a text.

    Parameters
    ----------
    word : str
    text : str

    Returns
    -------
    bool : True if word is in text, otherwise False.

    Examples
    --------
    >>> is_word_in_text("Python", "python is awesome.")
    True

    >>> is_word_in_text("Python", "camelCase is pythonic.")
    False

    >>> is_word_in_text("Python", "At the end is Python")
    True
    """
    pattern = r'(^|[^\w]){}([^\w]|$)'.format(word)
    pattern = re.compile(pattern, re.IGNORECASE)
    matches = re.search(pattern, text)
    return bool(matches)


if __name__ == '__main__':
    import doctest
    doctest.testmod()
Run Code Online (Sandbox Code Playgroud)

如果您的单词可能包含正则表达式特殊字符(例如+),那么您需要re.escape(word)