FeedRika API를 사용하여 추세 분석 도구 구축 - 1부 - 설정

WBOY
풀어 주다: 2024-07-20 09:16:39
원래의
695명이 탐색했습니다.

FeedRika API를 사용하여 추세 분석 도구 구축

저는 최근 감성 점수 및 관련 카테고리와 함께 최신 세계 뉴스를 제공하는 FeedRika라는 멋진 뉴스 API 서비스를 발견했습니다. 무료 사용 등급이 있으므로 사용해 보고 이를 통해 무엇을 구축할 수 있는지 알아보겠습니다.

내 아이디어 중 하나는 회사나 주제가 뉴스에서 어떻게 진행되었는지 확인할 수 있는 도구를 구축하는 것이었습니다.

Building a Trend Analysis Tool with the FeedRika API - Part I - Setup

공공 공간에서 특정 용어가 얼마나 인기 있는지 보여 주지만 검색량만 반영하는 Google 트렌드의 차트를 볼 수 있습니다. 주변의 감정이 긍정적인지 부정적인지에 대한 아이디어를 제공하지 않습니다. 따라서 뉴스를 샅샅이 뒤져 해당 주제가 호의적으로 쓰여지고 있는지 확인하고 비슷한 그래프를 표시하는 도구를 만들어 보겠습니다.

이 도구를 구축하기 위해 취할 광범위한 단계는 다음과 같습니다.

  1. 사용자로부터 검색할 주제를 수집
  2. Fedrika에서 주제와 일치하는 뉴스 기사를 가져옵니다
  3. 반환된 기사를 반복하여 각 기사에 대한 감정 점수를 추출합니다
  4. 이 점수를 차트에 표시하여 시각적으로 표시
  5. 평균 감정, 전체 긍정/부정 등 주제에 대한 추가 통계를 생성하려면 수학을 수행하세요...
  6. 사용자가 주제를 더 자세히 탐색할 수 있도록 원본 뉴스 기사를 사용자에게 표시합니다.

시작하기 전에

Fedrika 웹사이트에서 API 키를 받아 작업할 뉴스 기사를 가져오세요.
Feedrika.com으로 가서 계정을 등록하세요.

가입하고 나면 귀하의 프로필 페이지 Feedrika.com/profile에서 귀하의 신용 잔액 및 귀하가 요청한 내용을 보여주는 요청 로그와 함께 API 키를 확인할 수 있습니다.

Building a Trend Analysis Tool with the FeedRika API - Part I - Setup

플랫폼 선택

이 도구는 HTML, CSS 및 Javascript만으로 구축할 수 있지만 개인 API 키를 사용하는 것과 관련이 있으며 이를 인터넷을 통해 공개적으로 전송하는 것은 좋지 않으므로 node 및 express를 사용하여 서버에서 API 키를 숨기겠습니다. 환경 변수로 지정하고 비공개로 유지하세요.

저는 이 튜토리얼을 완전 초보자를 대상으로 맞춤화할 예정이므로 이미 node와 express에 익숙하다면 더 흥미로운 부분으로 건너뛰셔도 됩니다.

설정:

1. 노드와 익스프레스

Node 런타임 환경이 설치되어 있는지 확인하세요. 그렇지 않은 경우 여기에서 얻을 수 있습니다.

로컬 컴퓨터에 이 프로젝트에 대한 디렉토리를 만들고 그 내부를 탐색하세요.

터미널에서 npm init -y를 실행하여 노드 프로젝트를 기본값으로 초기화합니다.

실행: npm i express를 사용하여 Express 프레임워크를 설치합니다.
Express는 애플리케이션 내에서 페이지와 API 경로를 제공할 수 있는 간단한 웹 서버입니다. 설정이 쉽고 널리 사용되므로 온라인에서 도움말을 찾고 문제를 해결하는 것도 쉽습니다.

VSCode 또는 즐겨 사용하는 IDE에서 폴더를 열고 내부를 살펴보세요.

Building a Trend Analysis Tool with the FeedRika API - Part I - Setup

node_modules 폴더, package.json 파일, package-lock.json 파일이 있어야 합니다.

2. 첫 번째 경로 만들기

우리 앱에 사용자를 환영하는 인덱스 페이지를 만들어 보겠습니다
프로젝트 루트에 'welcome.html'이라는 새 파일을 만듭니다. 시작하려면 기본 정보만 입력하세요



    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome</title>


    <h1>This is my news trends app!</h1>

 
로그인 후 복사

첫 번째 경로를 설정하고 누군가 앱을 열면 이 Welcome.html 페이지를 반환해 보겠습니다

앱 루트에 'index.js' 파일을 생성하고 Express 프레임워크를 가져옵니다.

// Import the express framework
express = require("express");

// tell node that we are creating an express app
const app = express();

// define the port that the server will run on
const port = 3000;

// define the route for the index page
app.get("/", (req, res) => {
 res.sendFile(__dirname + "/welcome.html");
});

// Start the server and tell the app to listen for incoming connections on the port
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
로그인 후 복사

진행 상황을 테스트해 보겠습니다.
터미널에서 node index.js를 실행하세요. 서버가 실행 중이라는 확인 메시지가 표시됩니다

Building a Trend Analysis Tool with the FeedRika API - Part I - Setup

터미널에서 링크를 클릭하거나 브라우저에 붙여넣어 환영 페이지를 볼 수 있는지 확인하세요

Building a Trend Analysis Tool with the FeedRika API - Part I - Setup

3. 환경변수

API 키를 저장하기 위해 환경 변수를 설정해 보겠습니다.
프로젝트 루트에 '.env'라는 새 파일을 생성하세요.
Feedrika 프로필 페이지에서 API 키를 복사하여 여기에 붙여넣으세요

Building a Trend Analysis Tool with the FeedRika API - Part I - Setup

Let's also add a '.gitignore' file so we don't accidently upload this private key to the web

Building a Trend Analysis Tool with the FeedRika API - Part I - Setup

Now for some housekeeping

We don't want to start and stop the server from the terminal every time we make an edit to the app so let's setup auto reloading.

Open your package.json file and add these lines to the script object

"start": "node index.js",
"dev": "nodemon index.js -w"
로그인 후 복사

Building a Trend Analysis Tool with the FeedRika API - Part I - Setup

We are using nodemon with the '-w' flag to watch for changes in our root folder and restart the server.

Now we can start our server with the npm run dev command and it will automatically watch for changes and restart the server for us.

If you get an error about not recognizing nodemon run this to install it globally and try again:
npm i nodemon -g

Okay that completes the setup, lets move on to building out our App!

Let's update the welcome page and add a search box to ask for topics




    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome</title>
    <link rel="stylesheet" href="styles.css">



    <div id="container">
        <h1>News trends</h1>
        <h3>Search for a topic to get started</h3>
        <form class="search-form" action="/search" method="get">
            <input type="text" name="topic" placeholder="Search for a topic">
            <button type="submit">Search</button>
        </form>
    </div>



로그인 후 복사

Setup Stylesheets

Create a 'public' folder in the root of your project that will host our client side javascript, css and image files.
Add a 'styles.css' file to the public folder and add some basic styles for the welcome page

Building a Trend Analysis Tool with the FeedRika API - Part I - Setup

styles.css:

/* Import the Inter font */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap');

body {
    margin: 0;
    padding: 0;
    font-family: 'Inter', sans-serif;
}

#container {
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

/* SEARCH FORM */

.search-form input {
    padding: 1em;
    border: 1px solid #ccc;
    border-radius: 8px;
}

.search-form button {
    padding: 1em;
    border: 1px solid #ccc;
    border-radius: 8px;
    background-color: #313131;
    cursor: pointer;
    color: #fff;
}
로그인 후 복사

Now we need to tell express how to serve these static files so open 'index.js' and add this line:
app.use(express.static("public"));

Building a Trend Analysis Tool with the FeedRika API - Part I - Setup

You should be able to see the changes reflected right away, refresh the page in your browser and confirm

FeedRika API를 사용하여 추세 분석 도구 구축 - 1부 - 설정

Great! Let's now tell express how to handle this form submission

If you notice the form it submits to a '/search' endpoint so let's setup this route and handle the form submission

Open up your 'index.js' file and add these lines

// define the route for the /search endpoint
app.get("/search", (req, res) => {
  // get the query string from the request
  let query = req.query.topic;
  // send the query string back as the response
  res.send(query);
});
로그인 후 복사

FeedRika API를 사용하여 추세 분석 도구 구축 - 1부 - 설정

Let's test it out, go to your browser and enter a search term in the box and click submit
You should see a response from the server which shows your search term, like this

Building a Trend Analysis Tool with the FeedRika API - Part I - Setup

Good Job!

Now that we have a search route working let's plug-in the FeedRika API and fetch news for the topic.

Coming soon Part II - Fetching Data

위 내용은 FeedRika API를 사용하여 추세 분석 도구 구축 - 1부 - 설정의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!