2015-01-17 2 views
1

문장에 "go * to"구문이 포함되어 있는지 찾으려고합니다. 예를 들어, "go to", "go to"등입니다. Textblob를 사용하고 있습니다. 난 그냥 아래 사용할 수 있습니다 알고두 단어를 검색하는 파이썬 정규식

search_go_to = set(["go", "to"]) 
go_to_blob = TextBlob(var) 
matches = [str(s) for s in go_to_blob.sentences if search_go_to & set(s.words)] 
print(matches) 

하지만이 또한 같은 문장을 반환 "저기 가서 그에게이 가지고"내가 원하지 않는. 누구든지 내가 text.find ("go * to")와 같은 것을 어떻게 할 수 있는지 알고있다.

답변

3

한번에 사용하기 :

for match in re.finditer(r"go\s+\w+\s+to", text, re.IGNORECASE): 
0

이 방법이 유용합니까? 정규식에 대한

import re 
search_go_to = re.compile("^go.*to$") 
go_to_blob = TextBlob(var) 
matches = [str(s) for s in go_to_blob.sentences if search_go_to.match(str(s))] 
print(matches) 

설명 :

^ beginning of line/string 
go literal matching of "go" 
.* zero or more characters of any kind 
to literal matching of "to" 
$ end of line/string 

원하지 않는 경우

togo\\b (워드 경계)를 삽입, 일치하는 "것".

2

사용 generator expressions

>>> search_go_to = set(["go", "to"]) 
>>> m = ' .*? '.join(x for x in search_go_to) 
>>> words = set(["go over to", "go up to", "foo bar"]) 
>>> matches = [s for s in words if re.search(m, s)] 
>>> print(matches) 
['go over to', 'go up to'] 
1

을보십시오이

text = "something go over to something" 

if re.search("go\s+?\S+?\s+?to",text): 
    print "found" 
else: 
    print "not found" 

정규식을 : -

\s is for any space 
\S is for any non space including special characters 
+? is for no greedy approach (not required in OP's question) 
,

그래서 re.search("go\s+?\S+?\s+?to",text)"something go W#$%^^$ to something"과 물론 일치합니다. "something go over to something"

+0

이 답변은 조금 더 자세한 설명과 함께 할 수 있습니다. 아마도 단어와 비 단어 문자 유형, 비 탐욕적 인 물음표 등과 같은 정규 표현식의 부분을 설명하십시오. –