나는 이 단어를 사용하여 대한 정보를 찾을 수 있지만, 이 경우 일부 식별하면 구체화하십시오 - 스피드 수행할 수 있는 방법이 있으면 발표했다. I would like to 뭔가를해야합니다 다음과 같습니다.
if string.find(word):
print 'success'
어떤 도움도 주셔서 감사합니다.
if 'seek' in 'those who seek shall find':
print('Success!')
그러나 이 점에 유의하십시오 시퀀스일 일치시킵니다 문자, 단어 '& # 39 아니다 - 예를 들어, 전체 word& # 39;; # 39, & # 39 의 swordsmith&, '가 맞습니다. 정규 표현식 사용할 경우에만 로렌아줌마가 일치시키려면 단어, 할 일이 있습니다.
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 contains_word(s, w):
return (' ' + w + ' ') in (' ' + s + ' ')
contains_word('the quick brown fox', 'brown') # True
contains_word('the quick brown fox', 'row') # False
이 방법은 또한 우아한 가장 빠른. # 39, # 39 에 비해 휴 Bothwell& srdf/s 및 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
def contains_word(s, w):
return f' {w} ' in f' {s} '
나타내는 정수 되돌려줍니다 색인입니다 검색 항목을 찾을 수 있는 것으로 밝혀졌다. 이 경우, t com/downloads/global/corporate/iar/esg_prosupport. 되돌려줍니다 isn& # 39 - 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.'
이 작은 지정된 텍스트 검색 기능을 모두 비교한 것이다. 만약 모든 검색어를 텍스트 검색, 또는 '거짓' 그렇지 않으면, 길이 되돌려줍니다 발견된다.
는 유니코드 문자열 검색.
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')
일련의 문자를 일치하는 경우 충분하지 않다고 합니다 간단한 함수를 일치시키려면 단어, 이것은 해당 업무 완료. 기본적으로 필요한 그 문자열을 검색할 수 있는 공간 첨부됩니다 정보기술 (it):
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
이미 다른 문장 부호 (stripped 아웃해야 쉼표 및 가정합니다.
때 아닌, 내가 설명해볼건가 문자열으로 대해 한 마디도 묻지 않는 솔루션을 민감한 접두어 / 접미어는 무시하고 사례:
#!/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 포함될 경우 특수 문자 ('+' 와 같은) 그런 말을 하는 '레오 스카피 (word)'
고급 확인 방법을 찾아야 할 수 있는 정확한 단어, 오래 구체화하십시오:
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"
Regex 는 의 알 솔루션을 사용하여 복잡한 것이 그 사례.
텍스트를 로 단어 목록을 분할합니다 됩니다. (, 분리자를 num) 분할되었습니다 사용할 수 있는 방법. 이 모든 단어 목록을 되돌려줍니다 문자열의 분리자의 을 사용하여 seperator. 는 모든 it 의 경우 분리자를 미지정을 분할합니다 공백 (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"]
또한 고객 등 모든 쉼표 분할하려면 사용할 경우 다음과 같은 주장을 seperator
# 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'