使用 Python 检查字符串中是否存在单词
- 2024-12-25 08:51:00
- admin 原创
- 125
问题描述:
我正在使用 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]