spacy를 사용하여 엔티티 레이블로 대체 엔티티

Dec 17 2020

Spacy를 사용하여 각 엔티티를 레이블로 대체하여 데이터를 처리하고 싶습니다. 엔티티를 레이블 엔티티로 바꾸는 데 필요한 3000 개의 텍스트 행이 있습니다.

예를 들면 :

"조지아는 최근"무슬림 문화를 금지 "한 미국 최초의 주가되었습니다.

그리고 이렇게되고 싶어 :

"GPE는 최근 NORP 문화를 금지하는 ORDINAL GPE 상태가되었습니다. "

텍스트 행 이상을 코드로 대체하고 싶습니다.

매우 감사합니다.

예를 들어이 코드이지만 한 문장의 경우 s (문자열)를 3000 행을 포함하는 열로 수정하고 싶습니다.

첫 번째 : from ( SpaCy에서 엔티티를 레이블로 교체 )

s= "His friend Nicolas J. Smith is here with Bart Simpon and Fred."
doc = nlp(s)
newString = s
for e in reversed(doc.ents): #reversed to not modify the offsets of other entities when substituting
    start = e.start_char
    end = start + len(e.text)
    newString = newString[:start] + e.label_ + newString[end:]
print(newString)
#His friend PERSON is here with PERSON and PERSON.

두 번째 : from ( 명명 된 엔티티 주석을 사용하여 내 파일에 태그 병합 )

import spacy

nlp = spacy.load("en_core_web_sm")
s ="Apple is looking at buying U.K. startup for $1 billion" doc = nlp(s) def replaceSubstring(s, replacement, position, length_of_replaced): s = s[:position] + replacement + s[position+length_of_replaced:] return(s) for ent in reversed(doc.ents): #print(ent.text, ent.start_char, ent.end_char, ent.label_) replacement = "<{}>{}</{}>".format(ent.label_,ent.text, ent.label_) position = ent.start_char length_of_replaced = ent.end_char - ent.start_char s = replaceSubstring(s, replacement, position, length_of_replaced) print(s) #<ORG>Apple</ORG> is looking at buying <GPE>U.K.</GPE> startup for <MONEY>$1 billion</MONEY>

답변

1 SergeyBushmanov Dec 17 2020 at 13:45

IIUC, 다음을 통해 원하는 것을 얻을 수 있습니다.

  1. 파일에서 텍스트 읽기, 각 텍스트는 한 줄에 표시
  2. 엔티티 (있는 경우)를 태그로 대체하여 결과 처리
  3. 결과를 디스크에 기록하고 각 텍스트를 한 줄에 표시

데모:

import spacy
nlp = spacy.load("en_core_web_md")

#read txt file, each string on its own line
with open("./try.txt","r") as f:
    texts = f.read().splitlines()

#substitute entities with their TAGS
docs = nlp.pipe(texts)
out = []
for doc in docs:
    out_ = ""
    for tok in doc:
        text = tok.text
        if tok.ent_type_:
            text = tok.ent_type_
        out_ += text + tok.whitespace_
    out.append(out_)

# write to file
with open("./out_try.txt","w") as f:
    f.write("\n".join(out))

입력 파일의 내용 :

조지아는 최근 미국에서 "무슬림 문화를 금지 한 최초의 주가되었습니다.
그의 친구 Nicolas J. Smith가 Bart Simpon 및 Fred와 함께 있습니다.
Apple은 영국 스타트 업을 10 억 달러에 인수 할 계획입니다.

출력 파일의 내용 :

GPE는 최근 "NORP 문화를 금지하는 ORDINAL GPE 상태가되었습니다.
그의 친구 PERSON PERSON PERSON이 PERSON PERSON 및 PERSON과 함께 있습니다.
ORG는 MONEYMONEY MONEY를 위해 GPE 스타트 업을 구매하려고합니다.

노트 MONEYMONEY패턴을.

이 때문입니다:

doc = nlp("Apple is looking at buying U.K. startup for $1 billion")
for tok in doc:
    print(f"{tok.text}, {tok.ent_type_}, whitespace='{tok.whitespace_}'")

Apple, ORG, whitespace=' '
is, , whitespace=' '
looking, , whitespace=' '
at, , whitespace=' '
buying, , whitespace=' '
U.K., GPE, whitespace=' '
startup, , whitespace=' '
for, , whitespace=' '
$, MONEY, whitespace='' # <-- no whitespace between $ and 1
1, MONEY, whitespace=' '
billion, MONEY, whitespace=''