CoreNLP 情感分析 Python 遍历数据帧

CoreNLP Sentiment Analysis Python Loop through dataframe

如何让这段代码循环(运行)我数据框中的所有句子?

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"]))

上面执行时returns只有第一行句子:下面...

"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 函数的几种变体,但我得到的最好结果是所示的那个。

我的数据框名为 'reviews',只有一列(评论)。这是内容:

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

定义您的方法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)

return语句在for loop里面。由于return的属性是函数一执行就中断,所以函数会在第一个之后中断。

您需要做什么:

在循环开始之前制作一个var,在每个循环之后附加值。最后,将 return var 移出 for 循环,.