使用 Python 检查字符串中是否存在单词

2024-12-25 08:51:00
admin
原创
125
摘要:问题描述:我正在使用 Python,试图找出是否可以判断一个单词是否在字符串中。我找到了一些关于使用 识别单词是否在字符串中的信息.find,但是有没有办法做一个if陈述。我想要以下内容:if string.find(word): print("success") 解决方案 1:有...

问题描述:

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

我找到了一些关于使用 识别单词是否在字符串中的信息.find,但是有没有办法做一个if陈述。我想要以下内容:

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

解决方案 1:

有什么问题:

if word in mystring: 
   print('success')

解决方案 2:

if 'seek' in 'those who seek shall find':
    print('Success!')

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

import re

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

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

解决方案 3:

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

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

这种优雅的方法也是最快的。与 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'({0})'.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

编辑:对于 Python 3.6+,这个想法有一个小小的变体,速度同样快:

def contains_word(s, w):
    return f' {w} ' in f' {s} '

解决方案 4:

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

if word in string.split():
    print("success")

解决方案 5:

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.')

解决方案 6:

这个小函数比较给定文本中的所有搜索词。如果在文本中找到所有搜索词,则返回搜索的长度,否则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')

解决方案 7:

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

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

这假设逗号和其他标点符号已被删除。

解决方案 8:

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

您可以简单地将文本拆分为单词列表。为此使用split( separator , num )方法。它返回字符串中所有单词的列表,使用分隔符作为分隔符。如果未指定分隔符,它会在所有空格上进行拆分(您可以选择将拆分次数限制为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 = "     

" - space, tab, newline, return, formfeed
list_of_words = mystring.split(     

,.;!?'\"()")
if word in list_of_words:
    print('success')

解决方案 9:

由于您要求的是一个单词而不是一个字符串,我想提出一个不区分前缀/后缀且忽略大小写的解决方案:

#!/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()

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

解决方案 10:

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

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"of", text):
    if m.group(0):
        print("Present")
    else:
        print("Absent")

解决方案 11:

那么如何拆分字符串并去掉单词标点符号呢?

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.'))

我没有检查性能...

解决方案 12:

您只需在“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

解决方案 13:

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

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

import re

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

解决方案 14:

解决方案之一是在测试单词的开头和结尾处添加空格。如果单词位于句子的开头或结尾或位于任何标点符号旁边,则此方法会失败。我的解决方案是编写一个函数,将测试字符串中的任何标点符号替换为空格,并在测试字符串和测试单词的开头和结尾处添加空格,然后返回出现次数。这是一个简单的解决方案,无需任何复杂的正则表达式。

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”函数来测试该单词是否存在于字符串中

解决方案 15:

def word_find(word, string):
    # Using str.find() method
    # It returns -1 if the word is not found, else returns the index of the first occurrence
    if string.find(word) != -1:
        return 'success'
    else:
        return 'word not found in string'
    

print(word_find('lo', 'Hello world')) ## success

解决方案 16:

如果要查找字符串中单词或字符的所有实例的索引,请使用以下代码:

# This example finds indices of all instances of the character: '#'

x = "1)#welcome #to the #jungle 
life is very      # good"
f = 0
i = []
f = x.find('#')
i.append(f) 
while f != -1:
    f = x[i[-1]+1:].find('#')
    i.append(f+1+i[-1])  
print(i[:-1])

打印结果为:

#    [2, 11, 19, 43]
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1565  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1354  
  信创国产芯片作为信息技术创新的核心领域,对于推动国家自主可控生态建设具有至关重要的意义。在全球科技竞争日益激烈的背景下,实现信息技术的自主可控,摆脱对国外技术的依赖,已成为保障国家信息安全和产业可持续发展的关键。国产芯片作为信创产业的基石,其发展水平直接影响着整个信创生态的构建与完善。通过不断提升国产芯片的技术实力、产...
国产信创系统   21  
  信创生态建设旨在实现信息技术领域的自主创新和安全可控,涵盖了从硬件到软件的全产业链。随着数字化转型的加速,信创生态建设的重要性日益凸显,它不仅关乎国家的信息安全,更是推动产业升级和经济高质量发展的关键力量。然而,在推进信创生态建设的过程中,面临着诸多复杂且严峻的挑战,需要深入剖析并寻找切实可行的解决方案。技术创新难题技...
信创操作系统   27  
  信创产业作为国家信息技术创新发展的重要领域,对于保障国家信息安全、推动产业升级具有关键意义。而国产芯片作为信创产业的核心基石,其研发进展备受关注。在信创国产芯片的研发征程中,面临着诸多复杂且艰巨的难点,这些难点犹如一道道关卡,阻碍着国产芯片的快速发展。然而,科研人员和相关企业并未退缩,积极探索并提出了一系列切实可行的解...
国产化替代产品目录   28  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用