laravel api_使用Laravel和Google自然语言API进行情感分析

伯丁雷
2023-12-01

laravel api

by Darren Chowles

达伦·乔尔斯(Darren Chowles)

使用Laravel和Google自然语言API进行情感分析 (Sentiment Analysis Using Laravel and the Google Natural Language API)

在5分钟内写下您自己的情绪检查器。 (Write your own sentiment checker in 5 minutes.)

Sentiment Analysis is the process of determining whether a piece of text is positive, negative, or neutral.

情感分析是确定一段文字是肯定的,否定的还是中立的过程。

现实世界中的情感分析应用 (Real world applications for Sentiment Analysis)

The goal of this article is to get you up and running using the Google Natural Language API with Laravel. You’ll be using this API to perform sentiment analysis on text.

本文的目的是使您可以将Google自然语言API与Laravel结合起来使用。 您将使用此API对文本进行情感分析。

Using these techniques, you can build some great functionality into existing applications. Some ideas include:

使用这些技术,您可以在现有应用程序中构建一些强大的功能。 一些想法包括:

  • detecting sentiment in comments or reviews

    检测评论或评论中的情绪
  • forecasting market movements based on social media activity

    根据社交媒体活动预测市场走势
  • ascertaining the effectiveness of a marketing campaign by observing sentiment before and after

    通过观察前后的情绪来确定营销活动的有效性

解读情绪分析值 (Interpreting Sentiment Analysis values)

The Google API takes the provided text, analyzes it, and determines the prevailing emotional opinion. It determines whether the writing is positive, negative, or neutral.

Google API接受提供的文本,对其进行分析,然后确定主要的情感观点。 它确定书写是肯定的,否定的还是中性的。

The sentiment is represented by numerical score and magnitude values.

情绪由数字得分幅度值表示。

  • The score ranges between -1.0 (negative) and 1.0 (positive).

    分数在-1.0(负)和1.0(正)之间。

  • The magnitude indicates the strength of emotion (both positive and negative). The range spans from 0.0 to infinity. The magnitude is not normalized, so longer passages of text will always have a larger magnitude.

    大小表示情绪的强度(正负)。 范围从0.0到无穷大。 幅度未标准化,因此较长的文本段落始终具有较大的幅度

Google Cloud Platform设定 (Google Cloud Platform setup)

The first step involves creating a new project in the Google Cloud Platform console.

第一步涉及在Google Cloud Platform控制台中创建一个新项目。

Head over to the dashboard and create a new project.

转到仪表板并创建一个新项目

Once your project is created, keep the Project ID handy.

创建项目后,请随时保留项目ID

  • Once you have your project, go to the Create service account key page.

    完成项目后,转到“ 创建服务帐户密钥”页面。

  • Ensure your Sample project is selected at the top.

    确保在顶部选择了示例项目。
  • Under Service account, select New service account.

    在“ 服务帐户”下 ,选择“ 新服务帐户”

  • Enter a name in the Service account name field.

    服务帐户名称字段中输入名称

  • Under Role, select Project > Owner.

    在“ 角色”下 ,选择“ 项目 &g t; 哦, ner。

  • Finally, click Create to have the JSON credentials file downloaded automatically.

    最后,单击创建以自动下载JSON凭证文件。

You may also need to enable the Cloud Natural Language API via the API Library section.

您可能还需要通过“ API库”部分启用Cloud Natural Language API。

Laravel项目设置 (Laravel project setup)

The next step involves setting up a new Laravel project. If you already have an existing Laravel project, you can skip this step.

下一步涉及建立一个新的Laravel项目。 如果您已经有一个Laravel项目,则可以跳过此步骤。

I’m using Laravel 5.5 LTS for this article. In the command line, run the following Composer command to create a new project (you can also use the Laravel installer):

我在本文中使用Laravel 5.5 LTS。 在命令行中,运行以下Composer命令以创建一个新项目(您也可以使用Laravel安装程序 ):

composer create-project --prefer-dist laravel/laravel sample "5.5.*"

If you used Composer, rename the .env.example file to .env and run the following command afterwards to set the application key:

如果您使用的作曲家,重命名.env.example文件.ENV事后运行以下命令来设置应用程序键:

php artisan key:generate

添加Google“云语言”包 (Add the Google “cloud-language” package)

Run the following command to add the Google Cloud Natural Language package to your project:

运行以下命令以将Google Cloud Natural Language软件包添加到您的项目中:

composer require google/cloud-language

You may go ahead and place the downloaded JSON credentials file in your application root (NOT in your public directory). Feel free to rename it. Never commit this file to your code repo — the same goes for any sensitive settings. One option is to add it to the server manually after initial deployment.

您可以继续将下载的JSON凭证文件放置在应用程序根目录中(不在公共目录中)。 随时重命名。 切勿将此文件提交到您的代码存储库中-任何敏感设置都一样。 一种选择是在初始部署后将其手动添加到服务器。

主要事件:将实际代码添加到您的项目中 (The main event: adding the actual code to your project)

I’ll be adding the following route to my routes/web.php file:

我将以下路由添加到我的route / web.php文件中:

<?php
Route::get('/', 'SampleController@sentiment');

I’ve created a simple controller to house the code. I’ll be adding all the code within the controller. In a production application, I strongly suggest using separate service classes for any business logic. This way controllers are lean and stick to their original intention: controlling the input/output.

我创建了一个简单的控制器来存放代码。 我将在控制器中添加所有代码。 在生产应用程序中,我强烈建议对任何业务逻辑使用单独的服务类。 这样,控制器可以保持精简并坚持其最初意图:控制输入/输出。

We’ll start with a simple controller, adding a use statement to include the Google Cloud ServiceBuilder class:

我们将从一个简单的控制器开始,添加一个use语句以包括Google Cloud ServiceBuilder类:

<?php
namespace App\Http\Controllers;
use Google\Cloud\Core\ServiceBuilder;
class SampleController extends Controller{    public function sentiment()    {        // Code will be added here    }}

The first thing we’ll do is create an instance of the ServiceBuilder class so we can specify our Project ID and JSON credentials.

我们要做的第一件事是创建ServiceBuilder类的实例,以便我们可以指定项目ID和JSON凭据。

$cloud = new ServiceBuilder([    'keyFilePath' => base_path('gc.json'),    'projectId' => 'sample-207012']);

You specify the location of the JSON file using the keyFilePath option. I’ve used the Laravel base_path() helper to refer to the fully qualified app root path.

您可以使用keyFilePath选项指定JSON文件的位置。 我使用了Laravel base_path()帮助器来引用完全限定的应用程序根路径。

The next option is the projectId. This is the value you grabbed when you created the project in the GCP console.

下一个选项是projectId 。 这是在GCP控制台中创建项目时获取的值。

Next, we’ll create an instance of the LanguageClient class. The ServiceBuilder class makes it easy by exposing various factory methods which grant access to services in the API.

接下来,我们将创建LanguageClient类的实例。 通过公开各种工厂方法(可授予对API中服务的访问权限), ServiceBuilder类可轻松实现。

$language = $cloud->language();

Now that we have an instance of the class, we can start making use of the Natural Language API. We’ll declare a variable with some text, analyze the sentiment, and output the results:

现在我们有了该类的实例,我们可以开始使用自然语言API。 我们将使用一些文本声明一个变量,分析情感并输出结果:

// The text to analyse$text = 'I hate this - why did they not make provisions?';
// Detect the sentiment of the text$annotation = $language->analyzeSentiment($text);$sentiment = $annotation->sentiment();
echo 'Sentiment Score: ' . $sentiment['score'] . ', Magnitude: ' . $sentiment['magnitude'];

And that’s all there is to it!

这就是全部!

Here is the final controller class code:

这是最终的控制器类代码:

<?php
namespace App\Http\Controllers;
use Google\Cloud\Core\ServiceBuilder;
class SampleController extends Controller{    public function sentiment()    {        $cloud = new ServiceBuilder([            'keyFilePath' => base_path('gc.json'),            'projectId' => 'sample-207012'        ]);
$language = $cloud->language();
// The text to analyse        $text = 'I hate this - why did they not make provisions?';
// Detect the sentiment of the text        $annotation = $language->analyzeSentiment($text);        $sentiment = $annotation->sentiment();
echo 'Sentiment Score: ' . $sentiment['score'] . ', Magnitude: ' . $sentiment['magnitude'];    }}

结论 (Conclusion)

We’ve only scratched the surface of what the Google Natural Language API has to offer. Once you’ve come to grips with this, I suggest checking out the following additional services available in this API:

我们仅介绍了Google自然语言API所提供的内容。 一旦您掌握了这一点,建议您检查一下此API中提供的以下其他服务:

  • Entity Analysis: analyze entities like landmarks and public figures.

    实体分析 :分析地标和公众人物等实体。

  • Content Classification: analyze text and return a list of categories that apply to the content.

    内容分类 :分析文本并返回适用于该内容的类别列表。

If you have any questions — please feel free to make contact!

如有任何疑问,请随时与我们联系!

Originally published at www.chowles.com on June 13, 2018.

最初于2018年6月13日发布在www.chowles.com上。

翻译自: https://www.freecodecamp.org/news/sentiment-analysis-using-laravel-and-the-google-natural-language-api-acb70871698a/

laravel api

 类似资料: