Polarsimplementierung zum Erstellen von Objekten, die bestimmte Attribute auswählenPython

Python-Programme
Anonymous
 Polarsimplementierung zum Erstellen von Objekten, die bestimmte Attribute auswählen

Post by Anonymous »

Die Strophe Annotation -Pipeline verarbeitet einen Text und erstellt Satz s, die wiederum aus Word s umfassen. Dies sind Objekte, die von Strophe erstellt wurden. Ich möchte spezifische Attribute der Word -Objekte auswählen, die Stanza erstellt und meine eigenen Objekte in einer Liste von Listen erstellt (die äußere Liste ist der gesamte Text und die inneren Listen sind die Sätze). Mit einem Pandas DataFrame hat ich jede Textannotation in einer DataFrame -Zelle, ich würde eine Funktion mit einem Doppel für die Schleife erstellen, um dies zu erreichen. Ich möchte die Polars Bibliothek verwenden. Kann ich das mit den Polars api tun, oder ich mache das wie die Pandas Implementierung?

Code: Select all

import stanza
from typing import NamedTuple

nlp = stanza.Pipeline('en')

class Word(NamedTuple):
id: int
head_id: int
text: str
span: list[int]

def get_doc_words(doc: stanza.Document) -> list[list[Word]]:

doc_words = []
for sentence in doc.sentences:
sentence_words = []
for sent_word in sentence.words:
word = Word(
id=sent_word.id,
head_id=sent_word.head,
text=sent_word.text,
span=[sent_word.start_char, sent_word.end_char],
)
sentence_words.append(word)
doc_words.append(sentence_words)

return doc_words

df=pd.DataFrame(
{
'text': [
'This is some sample text. A second sentence.',
'And a second sample. Having a second sentence as well'
]
}
)
df['stanza_annotation'] = df['text'].apply(nlp)
df['stanza_words'] = df['stanza_annotation'].apply(get_doc_words)
< /code>
Und dies ist die Ausgabe, die ich für jeden Textstück erwarte.[[Word(id=1, head_id=5, text='This', span=[0, 4]),
Word(id=2, head_id=5, text='is', span=[5, 7]),
Word(id=3, head_id=5, text='some', span=[8, 12]),
Word(id=4, head_id=5, text='sample', span=[13, 19]),
Word(id=5, head_id=0, text='text', span=[20, 24]),
Word(id=6, head_id=5, text='.', span=[24, 25]],
[Word(id=1, head_id=3, text='A', span=[26, 27]),
Word(id=2, head_id=3, text='second', span=[28, 34]),
Word(id=3, head_id=0, text='sentence', span=[35, 43]),
Word(id=4, head_id=3, text='.', span=[43, 44])]]

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post