我正在使用Python,我试图找出你是否可以判断一个单词是否在字符串中。
我找到了一些关于识别单词是否在字符串中的信息-使用.find,但是否有一种方法来执行if语句。我想要这样的东西:
if string.find(word):
print("success")
我正在使用Python,我试图找出你是否可以判断一个单词是否在字符串中。
我找到了一些关于识别单词是否在字符串中的信息-使用.find,但是否有一种方法来执行if语句。我想要这样的东西:
if string.find(word):
print("success")
当前回答
出了什么问题:
if word in mystring:
print('success')
其他回答
由于您要求的是一个词,而不是一个字符串,我想提出一个解决方案,这是不敏感的前缀/后缀和忽略大小写:
#!/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)
您可以将字符串拆分为单词并检查结果列表。
if word in string.split():
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.'))
我没有检查性能……
如果匹配字符序列还不够,需要匹配整个单词,这里有一个简单的函数可以完成这项工作。它基本上是在必要的地方添加空格,并在字符串中搜索空格:
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
这里假设逗号和其他标点符号已经被去掉。
解决方案之一是在测试单词的开头和结尾放置一个空格。如果单词位于句首或句尾,或在任何标点符号旁边,则不适用。我的解决方案是编写一个函数,用空格替换测试字符串中的任何标点符号,并在开头和结尾或测试字符串和测试单词之间添加一个空格,然后返回出现的次数。这是一个简单的解决方案,不需要任何复杂的正则表达式。
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'中的函数来测试单词是否存在于字符串中