首页 > 解决方案 > 使用 spacy 将实体替换为实体标签

问题描述

我想通过使用 Spacy 用其标签替换每个实体来处理我的数据,并且我需要 3000 个文本行来用它们的标签实体替换实体,

例如:

“格鲁吉亚最近成为美国第一个“禁止穆斯林文化”的州。

并想变成这样:

“GPE 最近成为 ORDINAL GPE 州以“禁止 NORP 文化。"

我希望代码替换多行文本。

非常感谢。

例如这些代码但是对于一句话,我想修改s(字符串)到列包含3000行

第一个:来自(用 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.

第二个:来自(使用命名实体注释将标签合并到我的文件中

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>

标签: pythonnlpspacynamed-entity-recognition

解决方案


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 一起来到这里。
苹果正在考虑以 10 亿美元收购英国初创公司

输出文件内容:

GPE 最近成为 ORDINAL GPE 状态以“禁止 NORP 文化。
他的朋友 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=''

推荐阅读