Создать Spacy Doc, который имеет разделы - PullRequest
0 голосов
/ 13 декабря 2018

Мне интересно, что люди сделали для Spacy, когда хотят разбить документ на разные промежутки?Например, скажем, корпус из я создал документ Doc с ниже.Но для задачи, которую я делаю, я хочу создать индексацию для различных разделов, сохраняя при этом исходный объект.

doc = nlp("""
Patient History:
    This is paragraph 1.
Assessment:
    This is paragraph 2.
Signature:
    This is paragraph 3.
""")

Затем проанализируйте его так, что-то вроде:

doc.sections_ 

будетдоходность

["Patient History", "Assessment", "Signature"]

Ответы [ 2 ]

0 голосов
/ 17 декабря 2018

Это должно было бы прийти на шаге к файлу, очевидно, и не оптимизироваться для конвейера, но это мое немного хакерское решение.

  class ParsedNoteSections(object):
    """
        Pars notes into sections based on entity-tags. All sections are return as newly
        created doc objects.
    """



    def __init__(self,doc):
        self.doc = doc

    def get_section_titles(self):
    """Return the section header titles."""
    return [(e,e.start, e.end) for e in self.doc.ents if e.label_ == 'NOTESECTION']

    def original(self,doc):
        """Retrieve oringal doc object."""
        return self.doc

    def __repr__(self):
        return repr(self.doc)

    def parse_note_sections(self):
        """ Use entity sections as break-points to split original doc.

        Input: 
            None
        Output:
            List of section of objects stored in dictionary.
        """
        section_titles = self.get_section_titles()

        # stopgap for possible errors
        assert len(section_titles) > 0

        doc_section_spans = []
        for idx,section in enumerate(section_titles):
            section_label_new = section[0]
            label_start_new = section[1]
            label_end_new = section[2]

            # store first label
            if idx == 0:
                section_label_old = section_label_new
                continue

            # store last section
            elif idx == 1:
                section_label = section_label_old
                section_doc = self.doc[:label_start_new]

            # if on the last section
            elif idx == len(section_titles) - 1:
                section_label = section_label_old
                section_doc = self.doc[label_start_old:label_start_new]
                doc_section_spans.append({'section_label':section_label, 'section_doc':section_doc})

                section_label = section_label_new
                section_doc = self.doc[label_start_new:]

            # if not storing first or last section
            else:
                section_label = section_label_old
                section_doc = self.doc[label_start_old:label_start_new]

            label_start_old = label_start_new
            section_label_old = section_label_new

            doc_section_spans.append({'section_label':section_label, 'section_doc':section_doc})

        assert len(doc_section_spans) == len(section_titles)

        return doc_section_spans
0 голосов
/ 17 декабря 2018

SpaCy не поддерживает «разделы» - они не являются универсальной функцией документов, и способы их определения сильно различаются в зависимости от того, имеете ли вы дело с романом, академической газетой, газетой,и т. д.

Самое простое, что нужно сделать, это разделить документ самостоятельно, прежде чем подавать его в просторный формат.Если он отформатирован, как в вашем примере, это легко сделать, используя, например, отступ.

Если вы действительно хотите иметь только один объект Doc, вы сможете управлять им с расширением конвейера до spaCy.Смотри документацию здесь .

...