Анализ настроений CoreNLP Python L oop через фрейм данных - PullRequest
0 голосов
/ 09 апреля 2020

Как я могу сделать этот код l oop (выполнить) через все предложения в моем фрейме данных?

def get_sentiment(review):
    for text in review:
        senti = nlp.annotate(text,
                       properties={
                           'annotators': 'sentiment',
                           'outputFormat': 'json',
                           'timeout': 40000,
                       })

    #for i in senti["sentences"]:
        return ("{}: '{}': {} (Sentiment Value) {} (Sentiment)".format(
        s["index"],
        " ".join([t["word"] for t in s["tokens"]]),
        s["sentimentValue"], s["sentiment"]))

При выполнении вышеизложенного возвращается только первое предложение строки: Ниже ...

"0: 'you can see everything from thousands of years in human history it was an unforgettable and wonderful trip to paris for me': 3 (Sentiment Value) Positive (Sentiment)"

Я пробовал несколько вариантов для функции get_sentiment, но лучший результат, который я получаю, это показанный.

Мой фрейм данных называется «обзоры» и имеет один столбец (обзор). Это содержание:

                                                                                                 Review
0   you can see everything from thousands of years in human history it was an unforgettable and wonderful trip to paris for me
1   buy your tickets in advance and consider investing in one of many reputable tour guides that you can find online for at least part of your visit to the louvre these 2 arrangements will absolutely maximize your time and enjoyment of th...
2   quite an interesting place and a must see for art lovers the museum is larger than i expected and has so many exhibition areas that a full day trip might be needed if one wants to visit the whole place
3   simply incredible do not forget to get a three day pass if you love architecture art and history it is a must
4   we got here about 45 minutes before opening time and we were very first in line to get into the museum make sure to buy tickets ahead of time to help get in faster this museum is massive and can easily take your entire day an incredi...

Ответы [ 2 ]

0 голосов
/ 09 апреля 2020

Вы return оператор находится внутри for loop. Поскольку свойство return заключается в прерывании функции сразу после ее выполнения, функция прерывается сразу после первого.

Что нужно сделать, чтобы:

Создать var непосредственно перед запуском l oop, добавляйте значения после каждого l oop. И наконец, выведите return var из-за al oop,.

0 голосов
/ 09 апреля 2020

Определите свой метод get_sentiment следующим образом:

def get_sentiment(row):

    s = nlp.annotate(
        row.Review,
        properties={
            "annotators": "sentiment",
            "outputFormat": "json",
            "timeout": 40000,
        },
    )

    print(
        "{}: '{}': {} (Sentiment Value) {} (Sentiment)".format(
            row.index.iloc[0],
            " ".join([t["word"] for t in s["tokens"]]),
            s["sentimentValue"],
            s["sentiment"],
        )
    )

Используйте pandas .DataFrame.apply () и запустите:

>>> reviews.apply(get_sentiment, axis=1)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...