【问题标题】:Python - Tag all named entities with spacyPython - 用 spacy 标记所有命名实体
【发布时间】:2018-06-06 01:42:04
【问题描述】:

我创建了一个用 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

我可以标记所有可能让我绕过此错误的命名实体的替代方法是什么?不然怎么解决?

【问题讨论】:

  • 如果 ent.text 不是模式,请尝试 text = re.sub(re.escape(ent.text), ent.label_, text)

标签: python pandas spacy


【解决方案1】:

当然,您可以知道是哪一行导致了错误。只需添加一个 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2021-06-30
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多