我正在使用Python,我试图找出你是否可以判断一个单词是否在字符串中。
我找到了一些关于识别单词是否在字符串中的信息-使用.find,但是否有一种方法来执行if语句。我想要这样的东西:
if string.find(word):
print("success")
我正在使用Python,我试图找出你是否可以判断一个单词是否在字符串中。
我找到了一些关于识别单词是否在字符串中的信息-使用.find,但是否有一种方法来执行if语句。我想要这样的东西:
if string.find(word):
print("success")
当前回答
这个小函数比较给定文本中的所有搜索词。如果在文本中找到所有搜索词,则返回搜索长度,否则返回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')
其他回答
拆分字符串,剥离单词和标点符号怎么样?
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.'))
我没有检查性能……
我相信这个答案更接近最初的问题:在字符串中查找子字符串,但只有在整个单词?
它使用了一个简单的正则表达式:
import re
if re.search(r"\b" + re.escape(word) + r"\b", string):
print('success')
您可以将字符串拆分为单词并检查结果列表。
if word in string.split():
print("success")
使用regex是一种解决方案,但对于这种情况来说太复杂了。
您可以简单地将文本分割成单词列表。使用split(separator, num)方法。它返回字符串中所有单词的列表,使用分隔符作为分隔符。如果separator未指定,则对所有空格进行分割(您可以选择将分割的数量限制为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 = " \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')
这个小函数比较给定文本中的所有搜索词。如果在文本中找到所有搜索词,则返回搜索长度,否则返回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')