spaCy로 배우는 자연어 처리
Azadeh Mobasher
Principal Data Scientist
spaCy는 읽기 쉬운 프로덕션급 대안 Matcher 클래스를 제공함.
import spacy from spacy.matcher import Matchernlp = spacy.load("en_core_web_sm") doc = nlp("Good morning, this is our first day on campus.")matcher = Matcher(nlp.vocab)
pattern = [{"LOWER": "good"}, {"LOWER": "morning"}]matcher.add("morning_greeting", [pattern])matches = matcher(doc) for match_id, start, end in matches: print("Start token: ", start, " | End token: ", end, "| Matched text: ", doc[start:end].text)
>>> Start token: 0 | End token: 2 | Matched text: Good morning
in, not in 및 비교 연산자와 유사
| Attribute | Value type | Description |
|---|---|---|
IN |
any type | 속성 값이 목록에 포함됨 |
NOT_IN |
any type | 속성 값이 목록에 포함되지 않음 |
==, >=, <=, >, < |
int, float | 동등/비동등 비교 연산자 |
IN 연산자로 good morning과 good evening 모두 매칭doc = nlp("Good morning and good evening.")
matcher = Matcher(nlp.vocab)
pattern = [{"LOWER": "good"}, {"LOWER": {"IN": ["morning", "evening"]}}]
matcher.add("morning_greeting", [pattern])
matches = matcher(doc)
IN 연산자 사용 시 출력for match_id, start, end in matches:
print("Start token: ", start, " | End token: ", end,
"| Matched text: ", doc[start:end].text)
>>> Start token: 0 | End token: 2 | Matched text: Good morning
Start token: 3 | End token: 5 | Matched text: good evening
PhraseMatcher 클래스는 주어진 텍스트에서 긴 구문 목록을 매칭함.
from spacy.matcher import PhraseMatcher
nlp = spacy.load("en_core_web_sm")
matcher = PhraseMatcher(nlp.vocab)
terms = ["Bill Gates", "John Smith"]
patterns = [nlp.make_doc(term) for term in terms] matcher.add("PeopleOfInterest", patterns)doc = nlp("Bill Gates met John Smith for an important discussion regarding importance of AI.")matches = matcher(doc) for match_id, start, end in matches: print("Start token: ", start, " | End token: ", end, "| Matched text: ", doc[start:end].text)
>>> Start token: 0 | End token: 2 | Matched text: Bill Gates
Start token: 3 | End token: 5 | Matched text: John Smith
PhraseMatcher의 attr 인자를 사용할 수 있음matcher = PhraseMatcher(nlp.vocab, attr = "LOWER")terms = ["Government", "Investment"] patterns = [nlp.make_doc(term) for term in terms] matcher.add("InvestmentTerms", patterns) doc = nlp("It was interesting to the investment division of the government.")
matcher = PhraseMatcher(nlp.vocab, attr = "SHAPE")terms = ["110.0.0.0", "101.243.0.0"] patterns = [nlp.make_doc(term) for term in terms] matcher.add("IPAddresses", patterns) doc = nlp("The tracked IP address was 234.135.0.0.")
spaCy로 배우는 자연어 처리