spaCy에서 단일 용어 매칭하기
RegEx 패턴은 읽고, 작성하고, 디버깅하기가 쉽지 않습니다. 하지만 걱정하지 마세요. spaCy는 더 읽기 쉽고 프로덕션 수준으로 사용 가능한 대안인 Matcher 클래스를 제공합니다. Matcher 클래스는 미리 정의한 규칙을 주어진 Doc 컨테이너의 토큰 시퀀스에 매칭합니다. 이 연습 문제에서는 Matcher를 사용해 단일 단어를 찾는 방법을 연습해 보겠습니다.
example_text에서 해당 텍스트를 확인할 수 있고, nlp와 doc을 사용해 각각 example_text의 spaCy 모델과 Doc 컨테이너에 접근할 수 있어요.
이 연습은 강의의 일부입니다
spaCy로 배우는 자연어 처리
연습 안내
Matcher클래스를 초기화하세요.example_text에서 소문자witch에 매칭되는 패턴을 정의하세요.- 패턴을
Matcher클래스에 추가하고 매치를 찾으세요. - 매치 결과를 순회하며 시작·종료 토큰 인덱스와 매칭된 텍스트의 스팬을 출력하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
nlp = spacy.load("en_core_web_sm")
doc = nlp(example_text)
# Initialize a Matcher object
matcher = Matcher(nlp.____)
# Define a pattern to match lower cased word witch
pattern = [{"lower" : ____}]
# Add the pattern to matcher object and find matches
matcher.add("CustomMatcher", [____])
matches = matcher(____)
# Print start and end token indices and span of the matched text
for match_id, start, end in matches:
print("Start token: ", ____, " | End token: ", ____, "| Matched text: ", doc[____:____].text)