Python - 使用spacy标记所有命名实体

时间:2018-06-05 17:06:06

标签: python pandas spacy

我创建了一个用Spacy标记所有命名实体的函数:

def tag_ne(content):
    doc = nlp(content)
    text = doc.text
    for ent in doc.ents:
        text = re.sub(ent.text, ent.label_, text)
    return text

当我将它应用于小型Pandas系列的unicode字符串时,它可以工作。但是,当我将它应用到我的整个数据集时,我收到一个错误(因为特定观察引起的错误)。我无法知道导致错误的原因,我无法共享我的数据集,但错误如下:

---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-56-274bc594a3e7> in <module>()
----> 1 emails.content.apply(tag_ne)

/vol1/home/ccostello/.conda/envs/chris_/lib/python2.7/site-packages/pandas/core/series.pyc in apply(self, func, convert_dtype, args, **kwds)
   3190             else:
   3191                 values = self.astype(object).values
-> 3192                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   3193 
   3194         if len(mapped) and isinstance(mapped[0], Series):

pandas/_libs/src/inference.pyx in pandas._libs.lib.map_infer()

<ipython-input-46-6900d0e291db> in tag_ne(content)
      3     text = doc.text
      4     for ent in doc.ents:
----> 5         text = re.sub(ent.text, ent.label_, text)
      6     return text

/vol1/home/ccostello/.conda/envs/chris_/lib64/python2.7/re.pyc in sub(pattern, repl, string, count, flags)
    149     a callable, it's passed the match object and must return
    150     a replacement string to be used."""
--> 151     return _compile(pattern, flags).sub(repl, string, count)
    152 
    153 def subn(pattern, repl, string, count=0, flags=0):

/vol1/home/ccostello/.conda/envs/chris_/lib64/python2.7/re.pyc in _compile(*key)
    240         p = sre_compile.compile(pattern, flags)
    241     except error, v:
--> 242         raise error, v # invalid expression
    243     if len(_cache) >= _MAXCACHE:
    244         _cache.clear()

error: unbalanced parenthesis

我可以使用哪种替代方法标记可能让我解决此错误的所有命名实体?否则,我该如何解决?

1 个答案:

答案 0 :(得分:0)

当然,您可以知道导致错误的行。只需添加一个try / except语句:

def tag_ne(content):
    doc = nlp(content)
    text = doc.text
    for ent in doc.ents:
        try:
            text = re.sub(ent.text, ent.label_, text)
        except Exception as e:
            print(ent.text, ent.label_, '\n', e)
    return text