我正在使用Python,我试图找出你是否可以判断一个单词是否在字符串中。
我找到了一些关于识别单词是否在字符串中的信息-使用.find,但是否有一种方法来执行if语句。我想要这样的东西:
if string.find(word):
print("success")
我正在使用Python,我试图找出你是否可以判断一个单词是否在字符串中。
我找到了一些关于识别单词是否在字符串中的信息-使用.find,但是否有一种方法来执行if语句。我想要这样的东西:
if string.find(word):
print("success")
当前回答
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
其他回答
高级的方法来检查确切的单词,我们需要在一个长字符串中找到:
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")
出了什么问题:
if word in mystring:
print('success')
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
由于您要求的是一个词,而不是一个字符串,我想提出一个解决方案,这是不敏感的前缀/后缀和忽略大小写:
#!/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)
拆分字符串,剥离单词和标点符号怎么样?
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.'))
我没有检查性能……