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