Python - пометьте все именованные объекты с пространством - PullRequest
0 голосов
/ 05 июня 2018

Я создал функцию для пометки всех именованных объектов с помощью 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

Когда я применяю это к небольшому ряду строк Unicode в Pandas, это работает.Однако, когда я применяю его ко всему набору данных, я получаю ошибку (из-за ошибки, вызванной определенным наблюдением).У меня нет возможности узнать, что является причиной ошибки, и я не могу поделиться своим набором данных, но ошибка такова:

---------------------------------------------------------------------------
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 голосов
/ 05 июня 2018

Конечно, вы можете знать, какая строка вызывает ошибку.Просто добавьте оператор "попробовать / исключить":

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
...