从头算和密度泛函理论_PHP Laravel教程–如何从头开始构建关键字密度工具

从头算和密度泛函理论

Hello, freeCodeCamp readers. I hope I can bring you some great coding content for inspiration, education and of course, fun!

您好,freeCodeCamp读者。 希望我能带给您一些很棒的编码内容,以帮助您获得启发,教育和乐趣!

In this tutorial, we will learn about keyword density and how to build a tool that can calculate keyword density with Laravel.

在本教程中,我们将学习关键字密度以及如何构建可使用Laravel计算关键字密度的工具。

The web tool will allow us to paste in a full page of HTML. Then, magic will be executed to give us a precise keyword density score.

该网络工具将允许我们粘贴完整HTML页面。 然后,将执行魔术以为我们提供精确的关键字密度得分。

In a quick summary, here are some basic skills we will touch upon whilst building the tool.

简要概述一下,这是在构建工具时将涉及的一些基本技能。

  1. Laravel routes, controllers, and views

    Laravel路线,控制器和视图
  2. Laravel layouts

    Laravel布局
  3. HTML & forms

    HTML和表格
  4. JQuery & Ajax

    jQuery和Ajax
  5. Some native PHP

    一些本地PHP
  6. A bit of SEO!

    有点SEO!

什么是关键字密度? (What is keyword density?)

If you have your own website or blog, you possibly already know what keyword density is. For those who don't know what it means I will give a short and sweet explanation below.

如果您拥有自己的网站或博客,则可能已经知道什么是关键字密度。 对于那些不知道这意味着什么的人,我将在下面给出简短而甜美的解释。

Keyword density is a calculation of word or keyword occurrences usually in a large piece of text. The density is reported in a percentage which is simply calculated with the following formula.

关键字密度是通常在一大段文本中单词或关键字出现次数的计算。 密度以百分比报告,可通过以下公式简单计算。

KeywordDensity = (Keyword Count / Word Count) * 100

KeywordDensity =(关键字数/字数)* 100

为什么这很重要? (Why is this important?)

Keyword density is a key factor in the Google search engine algorithm. It is widely thought that a good keyword density for optimising web pages for Google rankings is around 3.5%. If the percentage is higher, for example 20%, then this could be seen as 'keyword stuffing' and therefore could badly affect your Google search rankings.

关键字密度是Google搜索引擎算法中的关键因素。 人们普遍认为,针对Google排名优化网页的良好关键字密度约为3.5%。 如果百分比较高,例如20%,则可能被视为“关键字填充”,因此可能会严重影响您的Google搜索排名。

So, that is a minuscule lesson on SEO and to give you a bit of context of what we are trying to build.

因此,这是关于SEO的一小节课,目的是让您了解我们正在尝试构建的内容。

使用Laravel构建关键字密度工具 (Building a Keyword Density Tool with Laravel)

This tutorial will presume we are all starting with a fresh Laravel build enabling anyone to follow on from any particular point. (Apologies if the beginning sections are telling you to suck eggs!)

本教程将假定我们都是从全新的Laravel构建开始,使任何人都可以从任何特定点继续学习。 (很抱歉,如果开始的部分告诉您要吮鸡蛋!)

Also, just for further context, I'm building this on MacOS with XAMPP locally.

另外,仅出于进一步考虑,我正在MacOS上使用XAMPP在本地进行构建。

先决条件 (Prerequisites)

  1. A PHP environment installed and access to the root directory

    已安装PHP环境并可以访问根目录
  2. Composer installed

    已安装作曲家
  3. Your favourite code editor that interprets PHP, HTML, CSS & JS.

    您最喜欢的解释PHP,HTML,CSS和JS的代码编辑器。

With all of these prerequisites checked off, we can now get our hands dirty.

选中所有这些先决条件后,我们现在就可以动手做。

创建我们的Laravel应用 (Creating Our Laravel App)

First of all we need to download and install a fresh Laravel build. Follow the steps below to achieve this.

首先,我们需要下载并安装新的Laravel版本。 请按照以下步骤来实现。

  1. Open your command line interface at the root directory of your web server, for example XAMPP⁩/⁨xamppfiles/⁩htdocs/

    在Web服务器的根目录中打开命令行界面,例如XAMPP⁩/⁨xamppfiles/⁩htdocs/
  2. Run the following command and let composer do it's magic

    运行以下命令,让作曲家神奇
composer create-project --prefer-dist laravel/laravel KeywordDensityApp

Top Tip: If you are working on MacOS, then check out the following steps to enable permissions on the Laravel storage folder.

顶提示:如果您使用的是MacOS,请查看以下步骤来启用Laravel存储文件夹上的权限。

  1. Navigate to your CLI to the project folder ('KeywordDensityApp')

    导航到CLI到项目文件夹('KeywordDensityApp')
  2. Run the following command

    运行以下命令
sudo chmod -R 777 storage/*

添加控制器和视图 (Adding a controller and view)

Now that we have the basics out of the way, we can start to build our controller and web page that will allow a user to paste in and analyse some HTML.

既然我们已经掌握了基础知识,那么我们可以开始构建控制器和网页,从而允许用户粘贴并分析一些HTML。

We can create a new controller in two ways: via the PHP artisan command line helper or simply by creating with your code editor. Feel free to use any of the below methods, just make sure the controller matches

我们可以通过两种方式创建新的控制器:通过PHP artisan命令行帮助器,或仅通过使用代码编辑器进行创建。 随意使用以下任何一种方法,只需确保控制器匹配

用PHP artisan创建控制器 (Create controller with PHP artisan)

php artisan make:controller ToolController

用代码编辑器创建控制器 (Create controller with code editor)

  1. Locate the following - ProjectFolder/App/Http/Controllers

    找到以下内容-ProjectFolder / App / Http / Controllers
  2. Create a new .php file named ToolController

    创建一个名为ToolController的新.php文件

Make sure this newly created file has the following contents:

确保此新创建的文件具有以下内容:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ToolController extends Controller
{
    //
}

Now let's create the view.

现在让我们创建视图。

使用代码编辑器创建视图 (Create view with code editor)

  1. Locate view folder under ProjectFolder/resources/views

    在ProjectFolder / resources / views下找到view文件夹
  2. Create a new folder named tool

    创建一个名为tool的新文件夹
  3. Create a new view PHP file named index.blade.php

    创建一个名为index.blade.php的新视图PHP文件。

现在让我们创建一个布局文件 (Now let's create a layout file)

With most Laravel applications, you will want to build a layouts file so that you don't have to repeat lots of HTML over and over to get the same design across the board.

对于大多数Laravel应用程序,您将需要构建一个布局文件,这样就不必一遍又一遍地重复许多HTML来获得全面的相同设计。

This layout is pretty basic, using a simple Bootstrap template and has a @yield call to the 'content' area which we will utilise in our views. In addition, there's a @yield call to 'scripts' which we will utilise later.

这种布局非常简单,使用一个简单的Bootstrap模板,并且对'content'区域具有@yield调用,我们将在我们的视图中使用它。 此外,还有一个@yield调用“脚本”,我们将在以后使用。

  1. Locate view folder under ProjectFolder/resources/views

    在ProjectFolder / resources / views下找到view文件夹
  2. Create a new folder here named layouts

    在此处创建一个名为layouts的新文件夹
  3. Create a new file named master.blade.php

    创建一个名为master.blade.php的新文件
  4. Add the following code to the file

    将以下代码添加到文件中
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Keyword Density Tool</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
          integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
    <meta name="csrf-token" content="{{ csrf_token() }}">
<style>
    body {padding-top: 5em;}
</style>
</head>
<body>

<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
    <a class="navbar-brand" href="#">Keyword Density App</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarsExampleDefault">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item">
                <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item active">
                <a class="nav-link" href="{{route('KDTool')}}">Tool</a>
            </li>
        </ul>

    </div>
</nav>

<main role="main" class="container mt-3">

    @yield('content')

</main><!-- /.container -->

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
@yield('scripts')
</body>
</html>

扩展视图以使用布局文件 (Extend our views to use the layout file)

Let us now use the newly created layouts file in both our welcome view and tool index view. Follow these steps to extend to the layout.

现在让我们在欢迎视图和工具索引视图中使用新创建的布局文件。 请按照以下步骤扩展到布局。

  1. Add the following code to both ProjectFolder/resources/views/welcome.blade.php and ProjectFolder/resources/views/tool/index.blade.php

    将以下代码添加到ProjectFolder / resources / views / welcome.blade.php和ProjectFolder / resources / views / tool / index.blade.php
@extends('layouts.master')

@section('content')
    

@endsection

Try rendering the index page of the tool directory, for example localhost/tool. It should look something like below.

尝试呈现工具目录的索引页,例如localhost / tool。 它看起来应该像下面这样。

链接控制器,路线和视图 (Linking up the Controller, Route, & View)

Now that we have a controller and view we need to first define a route and second add a return view method to the controller.

现在我们有了一个控制器和视图,我们首先需要定义一条路线,然后向该控制器添加一个return view方法。

定义路线 (Define the route)

  1. Locate web routes file under ProjectFolder/routes/web.php

    在ProjectFolder / routes / web.php下找到Web路由文件
  2. Add the following code to the bottom of the file:

    将以下代码添加到文件的底部:
Route::get('/tool', 'ToolController@index')->name('KDTool');

创建新的控制器方法 (Create the new controller method)

Now, go back to your ToolController and add the following function:

现在,回到您的ToolController并添加以下功能:

public function index()
{
   return view('tool.index');
}

Feel free to change the view names, route URLs, or controller functions to your personal liking. Just make sure they all match up and the page renders.

可以根据自己的喜好随意更改视图名称,路由URL或控制器功能。 只要确保它们都匹配并呈现页面即可。

建立我们的工具视图 (Building up our tool view)

Now, with our earlier set up of views and layout files, we can start to add the content in the form of HTML that we are going to need. It will consist of nothing more than some text, textarea input form, and a submit button.

现在,通过我们先前设置的视图和布局文件,我们可以开始以我们需要HTML形式添加内容。 它仅包含一些文本,textarea输入表单和一个提交按钮。

Add the following HTML to the content section of the ProjectFolder/resources/views/tool/index.blade.php file.

将以下HTML添加到ProjectFolder / resources / views / tool / index.blade.php文件的内容部分。

<form id="keywordDensityInputForm">
        <div class="form-group">
            <label for="keywordDensityInput">HTML or Text</label>
            <textarea class="form-control" id="keywordDensityInput" rows="12"></textarea>
        </div>
        <button type="submit" class="btn btn-primary mb-2">Get Keyword Densities</button>
    </form>

The view should now render like this:

视图现在应如下所示:

建立前端和后端之间的桥梁 (Creating the bridge between the front end and the back end)

Now, we pretty much have everything we need on the front end: a simple input text area where users can paste in their plain text or HTML. What's missing is the logic for when the button is pressed 'Get Keyword Densities'.

现在,我们几乎已经有了前端所需的一切:一个简单的输入文本区域,用户可以在其中粘贴其纯文本或HTML。 缺少的是单击按钮“获取关键字密度”时的逻辑。

This bridging logic will essentially do the following.

这种桥接逻辑实质上将执行以下操作。

  1. Listen for clicks on the Get Keyword Density Button

    监听“获取关键字密度”按钮上的点击
  2. Grab the contents of the non-empty text area input

    抓取非空文本区域输入的内容
  3. Use JQuery Ajax to send the data to the backend to be processed and await a response.

    使用JQuery Ajax将数据发送到后端进行处理并等待响应。
  4. When the response is passed back, handle the data and create a HTML table with the human-readable statistics (keyword density).

    返回响应后,处理数据并创建具有人类可读统计信息(关键字密度)HTML表。

前端 (Front end)

To do this we will use an in-page script which we can inject using the @section tag.

为此,我们将使用页内脚本,可以使用@section标记进行注入。

Add the following to the tool/index.blade.php view, after the content section.

在内容部分之后,将以下内容添加到tool / index.blade.php视图中。

@section ('scripts')
    <script>
        $('#keywordDensityInputForm').on('submit', function (e) { // Listen for submit button click and form submission.
            e.preventDefault(); // Prevent the form from submitting
            let kdInput = $('#keywordDensityInput').val(); // Get the input
            if (kdInput !== "") { // If input is not empty.
			// Set CSRF token up with ajax.
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });

                $.ajax({ // Pass data to backend
                    type: "POST",
                    url: "/tool/calculate-and-get-density",
                    data: {'keywordInput': kdInput},
                    success: function (response) {
                        // On Success, build a data table with keyword and densities
                        if (response.length > 0) {
                            let html = "<table class='table'><tbody><thead>";
                            html += "<th>Keyword</th>";
                            html += "<th>Count</th>";
                            html += "<th>Density</th>";
                            html += "</thead><tbody>";

                            for (let i = 0; i < response.length; i++) {
                                html += "<tr><td>"+response[i].keyword+"</td>";
                                html += "<td>"+response[i].count+"</td>";
                                html += "<td>"+response[i].density+"%</td></tr>";
                            }

                            html += "</tbody></table>";

                            $('#keywordDensityInputForm').after(html); // Append the html table after the form.
                        }
                    },
                });
            }
        })
    </script>
@endsection

This entire script that we inject will handle all of the numbered list items above.

我们注入的整个脚本将处理上面所有编号的列表项。

What is left to do is handle the data coming in on the back end side of things.

剩下要做的就是处理后端的数据。

后端 (Back end)

Firstly, before we go any further with coding, we need to handle the fact that both plain text and HTML can be submitted. For this we can use a nifty tool to help us out.

首先,在继续进行编码之前,我们需要处理一个事实,即纯文本和HTML都可以提交。 为此,我们可以使用一个漂亮的工具来帮助我们。

html2text is the perfect PHP library for this use case, so it's time we install it. html2text does exactly what it says on the tin, converts HTML markup to plain text.

html2text是此用例的理想PHP库,因此是时候安装它了。 html2text完全如其所言,将HTML标记转换为纯文本。

Luckily, this package has a composer install command, so enter the following command into the CLI on the projects root directory.

幸运的是,此软件包具有composer install命令,因此请在项目根目录的CLI中输入以下命令。

composer require html2text/html2text

Now, our backend controller is going to receive either HTML or plain text in requests firing from the HTML form we created in our view. We now need to make the route to handle this call and to route the call to the specific controller that will work the magic.

现在,我们的后端控制器将在我们在视图中创建HTML表单中触发的请求中接收HTML或纯文本。 现在,我们需要进行路由以处理此呼叫,并将该呼叫路由到将起作用的特定控制器。

Add the following PHP to the web.php routes file:

将以下PHP添加到web.php路由文件中:

Route::post('/tool/calculate-and-get-density', 'ToolController@CalculateAndGetDensity');

Secondly, add the following to ToolController.php file:

其次,将以下内容添加到ToolController.php文件中:

public function CalculateAndGetDensity(Request $request) {
        if ($request->isMethod('GET')) {

          

        }
    }

OK, so the stage is set. Let's code in the magic that will calculate the keyword density and return the data.

好,就可以了。 让我们编写魔术代码,以计算关键字密度并返回数据。

Firstly, add use statement is required for the newly installed html2text package. Add the following to the top of the ToolController.php, just below other use statements:

首先,新安装的html2text包需要添加use语句。 将以下内容添加到ToolController.php的顶部,紧随其他use语句之后:

use Html2Text\Html2Text;

Then we need to handle the get parameter that is to be passed in, making sure it's not set and then converting the parameter of content to plain text. Refactor the CalculateAndGetDensity function to look like below:

然后,我们需要处理要传入的get参数,确保未设置该参数,然后将content的参数转换为纯文本。 重构CalculateAndGetDensity函数,如下所示:

public function CalculateAndGetDensity(Request $request) {
        if ($request->isMethod('GET')) {

            if (isset($request->keywordInput)) { // Test the parameter is set.
                $html = new Html2Text($request->keywordInput); // Setup the html2text obj.
                $text = $html->getText(); // Execute the getText() function.


            }

        }
    }

Now that we have a variable to hold all of the text stripped for the keywordInput parameter, we can go ahead and start to calculate density.

现在我们有了一个变量来保存为keywordInput参数剥离的所有文本,我们可以继续并开始计算密度。

We need to handle the following:

我们需要处理以下问题:

  1. Determine the total count of words

    确定单词总数
  2. Analyse the textual string and convert it to a key value array (the key being the keyword, the value being the occurrence of the word)

    分析文本字符串并将其转换为键值数组(键为关键字,值为单词的出现)
  3. Sort into order by descending with the biggest occurrence first in the array

    通过降序排列,以出现次数最多的数组为先
  4. Loop over the key and value array, pushing the values to a new array with an additional field of 'density' which utilises the keyword density formula we looked at earlier in the article. This formula will use the value (occurrence) and the total word count.

    循环遍历键和值数组,将值推到具有“ density”附加字段的新数组,该字段利用了我们在本文前面介绍的关键字density公式。 此公式将使用值(出现)和总字数。
  5. Finally, to return the data

    最后,返回数据

Refactor the function to look like the following, taking note of the comments:

将该函数重构为如下所示,并注意以下注释:

public function CalculateAndGetDensity(Request $request) {
        if ($request->isMethod('GET')) {

            if (isset($request->keywordInput)) { // Test the parameter is set.
                $html = new Html2Text($request->keywordInput); // Setup the html2text obj.
                $text = strtolower($html->getText()); // Execute the getText() function and convert all text to lower case to prevent work duplication
                $totalWordCount = str_word_count($text); // Get the total count of words in the text string
                $wordsAndOccurrence  = array_count_values(str_word_count($text, 1)); // Get each word and the occurrence count as key value array
                arsort($wordsAndOccurrence); // Sort into descending order of the array value (occurrence)

                $keywordDensityArray = [];
                // Build the array
                foreach ($wordsAndOccurrence as $key => $value) {
                    $keywordDensityArray[] = ["keyword" => $key, // keyword
                        "count" => $value, // word occurrences
                        "density" => round(($value / $totalWordCount) * 100,2)]; // Round density to two decimal places.
                }

                return $keywordDensityArray;
            }
        }
    }

Note: The beauty of html2text is that it doesn't really care if it's converting HTML or plain text in the first place, so we don't need to worry if a user submits either. It will still churn out plain text.

注意: html2text的优点在于,它实际上并不关心它是首先转换HTML还是纯文本,因此我们不必担心用户是否提交了。 它仍然会产生纯文本。

进行测试 (Putting it to the test)

Finally, we are ready to test the tool, wahoo! Go ahead and render the tool index view (localhost/tool).

最后,我们准备测试该工具wahoo! 继续并呈现工具索引视图(localhost / tool)。

  1. Now, you can go to any website of your choice on the web, load a page from that site, right click and click view source.

    现在,您可以转到网络上您选择的任何网站,从该网站加载页面,右键单击并单击查看源。
  2. Copy the entire contents and come back to the tool.

    复制全部内容,然后返回到该工具。
  3. Paste the contents into the text area and click the Get Keyword Densities button.

    将内容粘贴到文本区域,然后单击“获取关键字密度”按钮。
  4. Await the response and check out the table of keyword densities!

    等待响应,并查看关键字密度表!
  5. Check out my example below which uses the HTML of this page.

    在下面查看我的示例,该示例使用此页面HTML。

And that is it!

就是这样!

摘要 (Summary)

In this article we learned how to build a Laravel application from scratch. It touched on some of the different parts of the full stack in development such as JQuery, PHP, HTML etc. Hopefully, with the understanding of this application, the same methodology can be used to build something else, perhaps bigger and better.

在本文中,我们学习了如何从头开始构建Laravel应用程序。 它涉及开发中整个堆栈的某些不同部分,例如JQuery,PHP,HTML等。希望,在了解了此应用程序之后,可以使用相同的方法来构建其他东西,也许更大或更更好。

可能的进一步发展 (Possible further developments)

The keyword density tool currently takes 'stop' words into account. Stop words are known to be ignored by Googles crawlers. Words such as it, the, as, and a. Looking at the tool screenshot above, you can see that they are used a lot!

关键字密度工具当前考虑了“停止”字词。 众所周知,停用词会被Google的抓取工具忽略。 单词it,the,as和a。 查看上面的工具屏幕截图,您会发现它们已被大量使用!

Further development could be carried out to filter the stop words and only calculate density on the non-stop words which is potentially a better view for SEO scoring.

可以进行进一步的开发以过滤停用词并仅计算非停用词的密度,这对于SEO评分可能是一个更好的视图。

I hope you enjoyed this article! If you did, feel free to check out my blog, https://www.codewall.co.uk/

希望您喜欢这篇文章! 如果您愿意,请随时查看我的博客https://www.codewall.co.uk/

Until next time!

直到下一次!

翻译自: https://www.freecodecamp.org/news/how-to-build-a-keyword-density-tool-with-laravel/

从头算和密度泛函理论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值