我编写了一段代码来查找字符串中存在的位置。
import spacy
nlp= spacy.load('en')
doc1='Pune, India'
doc2='India, Pune'
doc3='Pune India'
doc4='India Pune'
print([(X.text, X.label_) for X in nlp(doc1).ents])
print([(X.text, X.label_) for X in nlp(doc2).ents])
print([(X.text, X.label_) for X in nlp(doc3).ents])
print([(X.text, X.label_) for X in nlp(doc4).ents])我的输出是:
[('India', 'GPE')]
[('India', 'GPE'), ('Pune', 'GPE')]
[('India', 'GPE')]
[('India', 'GPE')]我怎样才能得到(‘印度’,'GPE'),('Pune','GPE')所有人的相同输出?
发布于 2019-11-01 15:40:16
因为doc2中的印度后面有逗号(,),所以SpaCy才能理解'Pune‘可能是一个GPE。对于其他三个示例,情况并非如此,它只检测到一个已知的GPE,即印度。
您可能需要根据数据集中的情况编写一些自定义代码。您可以尝试在检测到的GPEs中考虑“之前”和“之后”这两个单词,并检查它们是否出现在英语词典中。例如,在仅检测到“印度”的情况下,您可以在英语单词列表中检查“Pune”(您可以在SpaCy中获取它),如果它不存在,则可以将其视为候选GPE。
如果你在编码方面需要帮助,一定要让我知道?
发布于 2019-11-02 22:43:10
这是因为您使用的模型不知道'Pune‘是一个标签为'GPE’的实体。
你可以用add_pipe()在你的管道中添加一个额外的组件,将'Pune‘也标识为一个实体。
请注意,逗号的存在并不是'Pune‘被归类为实体的原因。
既然您得到了一个文本列表,那么让我们创建一个列表,以便可以使用match nlp.pipe()。
texts = ['Pune, India', 'India, Pune', 'Pune India', 'India Pune']
LOCATIONS = ["Pune", "India"]首先,你要找出文本中出现'Pune‘的地方。PhraseMatcher可以用来实现这个目的。
from spacy.matcher import PhraseMatcher创建一个matcher对象,并向其中添加要识别的模式。
nlp = spacy.load('en')
matcher = PhraseMatcher(nlp.vocab)
matcher.add("LOCATIONS", None, *list(nlp.pipe(LOCATIONS)))现在定义组件函数。
def places_component(doc):
doc.ents = [Span(doc, start, end, label="GPE") for match_id, start, end in matcher(doc)]
return doc将组件添加到管道中。
nlp.add_pipe(places_component) #last=True现在试一下
for doc in nlp.pipe(texts):
print([(ent.text, ent.label_) for ent in doc.ents])你会得到
[('Pune', 'GPE'), ('India', 'GPE')]
[('India', 'GPE'), ('Pune', 'GPE')]
[('Pune', 'GPE'), ('India', 'GPE')]
[('India', 'GPE'), ('Pune', 'GPE')]整个程序应该是这样的
import spacy
from spacy.tokens import Span
from spacy.matcher import PhraseMatcher
LOCATIONS = ["Pune", "India"]
texts = ['Pune, India', 'India, Pune', 'Pune India', 'India Pune']
nlp = spacy.load('en')
matcher = PhraseMatcher(nlp.vocab)
matcher.add("LOCATIONS", None, *list(nlp.pipe(LOCATIONS)))
def places_component(doc):
doc.ents = [Span(doc, start, end, label="GPE") for match_id, start, end in matcher(doc)]
return doc
nlp.add_pipe(places_component) #last=True
for doc in nlp.pipe(texts):
print([(ent.text, ent.label_) for ent in doc.ents])https://stackoverflow.com/questions/58655497
复制相似问题