使用spacy替换实体及其实体标签



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

例如:

"佐治亚州最近成为美国第一个";禁止穆斯林文化">

想要变成这样:

"GPE最近成为普通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>

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最近变成了普通GPE状态;禁止NORP文化
他的朋友PERSON PERSON与PERSON和PERSON在一起
ORG正在考虑为MONEYMONEY 收购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=''

最新更新