spacyを使用したエンティティラベルでの置換エンティティ

Dec 17 2020

Spacyを使用して各エンティティをそのラベルに置き換えることでデータを処理したいのですが、エンティティをラベルエンティティに置き換えるには3000のテキスト行が必要です。

例えば:

「ジョージアは最近、「イスラム文化を禁止する」最初の米国の州になりました。

そして、このようになりたい:

「GPEは最近、NORP文化を禁止するための通常のGPE州になりました。「」

テキストの行以上をコードで置き換えたい。

どうもありがとう。

たとえば、これらのコードですが、1つの文について、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.

2番目: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))

入力ファイルの内容:

ジョージア州は最近、「イスラム文化を禁止した最初の米国の州になりました。
彼の友人であるニコラスJ.スミスはバートシンプソンとフレッドと共にここにいます。
アップルは英国のスタートアップを10億ドルで購入することを検討しています。

出力ファイルの内容:

GPEは最近、「NORP文化を禁止する」という序数のGPE州になりました。
彼の友人であるPERSON PERSON PERSONは
、PERSONPERSONとPERSONと共にここにいます。ORGはMONEYMONEYMONEYの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=''