Python-检查单词是否在字符串中
我正在使用PythonV2,我正在尝试找出您是否可以判断单词是否在字符串中 我发现了一些关于使用.find识别字符串中是否有单词的信息,但是有没有一种方法可以执行if语句呢。我想要以下的东西:Python-检查单词是否在字符串中,python,string,Python,String,我正在使用PythonV2,我正在尝试找出您是否可以判断单词是否在字符串中 我发现了一些关于使用.find识别字符串中是否有单词的信息,但是有没有一种方法可以执行if语句呢。我想要以下的东西: if string.find(word): print 'success' 感谢您的帮助。以下问题是什么: if word in mystring: print 'success' find返回一个整数,表示搜索项所在位置的索引。如果找不到,则返回-1 haystack = 'asdf
if string.find(word):
print 'success'
感谢您的帮助。以下问题是什么:
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
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
重新导入
def findWholeWord(w):
返回re.compile(r'\b({0})\b'.format(w),flags=re.IGNORECASE.search
FindHoleword(“寻找”)(“寻找的人会发现”)#->
findWholeWord('word')('browshmith')#->无
如果匹配一个字符序列是不够的,您需要匹配整个单词,这里有一个简单的函数来完成这项工作。它基本上会在必要时追加空格,并在字符串中搜索:
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
这假设逗号和其他标点符号已经去掉。这个小函数比较给定文本中的所有搜索词。如果在文本中找到所有搜索词,则返回搜索长度,否则返回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')
你可以在“word”前后加一个空格
这样,它会查找“单词”前后的空格
如果您想知道整个单词是否位于空格分隔的单词列表中,只需使用:
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'\b({0})\b'.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} '
高级方式检查我们需要在长字符串中查找的确切单词:
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 string.split():
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()
如果您的单词可能包含regex特殊字符(例如+
),那么您需要re.escape(word)
,使用regex是一种解决方案,但对于这种情况来说太复杂了
您可以简单地将文本拆分为单词列表。使用拆分(分隔符,num)方法。它返回字符串中所有单词的列表,使用分隔符作为分隔符。如果未指定分隔符,它将在所有空格上拆分(可选地,您可以将拆分数量限制为num)
这不适用于带有逗号等的字符串。例如:
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'
如何拆分字符串并去掉单词标点符号
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.'))
我没有检查性能…作为警告,如果你有一个字符串“paratyphoid is bad”,并且在“paratyphoid is bad”中做了一个if“typoid”,那么你会得到一个true。有人知道如何克服这个问题吗?@user2567857,正则表达式——请参见Hugh Bothwell的答案。if(mystring中的word1和mystring中的word2)这怎么是公认的答案?!!它只是检查字符串中是否出现一个字符序列(而不是一个单词)。此解决方案最适合我的情况,因为我使用的是标记化的空格分隔字符串。这是我最喜欢的答案:)我同意,但最快的解决方案不会像re.compile(…那样忽略大小写。这有几个问题:(1)结尾的单词(2)开头的单词(3)中间的单词,如包含单词(“说”,“西蒙说:不要用这个答案”)
@Martintoma-如上所述,这种方法专门用于找出“整个单词是否在一个空格分隔的单词列表中”。在这种情况下,它适用于:(1)结尾的单词(2)开头的单词(3)单词之间。您的示例之所以失败,是因为您的单词列表中包含冒号。@JeffHeaton再次强调,此方法专门用于“如果您想确定整个单词是否位于空格分隔的单词列表中”,正如作者明确指出的那样。请使用链接解释此代码的工作原理,而不仅仅是给出代码,因为解释更有可能帮助未来的读者。这应该是匹配整个单词的实际答案。我们也应该考虑标点符号。看。但是如果单词位于句子的开头或结尾怎么办(没有空间)有没有一种真正快速的方法可以搜索多个单词,比如说一组几千个单词,而不必在每个单词之间构建for循环?我有一百万个句子,一百万个词汇要搜索,看看哪个句子有哪些匹配的单词。目前我花了好几天的时间来处理,我想知道是否有“这是一种更快的方法。@Tom尝试使用grep而不是python regexp1 for Swarchmith如何处理异常,例如,当字符串中找不到单词时?@FaCoffee:如果找不到字符串,函数将返回None(参见上面的最后一个示例)这是一个很好的解决方案,类似于@ Corvax,有助于添加普通字符来拆分,这样在一个字符串中,如“先:……”,可以找到“第一”这个词。请注意,@ tStunko不包括“附加字符中的“:”:我会:),而且,如果搜索不区分大小写,请考虑使用.LUVER()。在拆分之前的单词和字符串上。mystring.lower().split()
和word.lower()
我认为这也比正则表达式示例快。我认为使用类似于split(\t\n\r\f,.;!?“\”()”
的方法,我们需要导入re
,但这也是一个很好的解决方案。“接受的”答案不完整。它失败了
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.'))