{"id":13468719,"url":"https://github.com/thisandagain/sentiment","last_synced_at":"2025-05-13T22:01:54.054Z","repository":{"id":4961717,"uuid":"6119227","full_name":"thisandagain/sentiment","owner":"thisandagain","description":"AFINN-based sentiment analysis for Node.js.","archived":false,"fork":false,"pushed_at":"2020-05-18T13:55:58.000Z","size":416,"stargazers_count":2660,"open_issues_count":16,"forks_count":309,"subscribers_count":57,"default_branch":"develop","last_synced_at":"2025-05-10T00:05:55.609Z","etag":null,"topics":["afinn","analysis","javascript","nlp","sentiment","sentiment-analysis"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/thisandagain.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2012-10-08T03:45:22.000Z","updated_at":"2025-05-06T10:05:20.000Z","dependencies_parsed_at":"2022-07-13T13:50:53.117Z","dependency_job_id":null,"html_url":"https://github.com/thisandagain/sentiment","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thisandagain%2Fsentiment","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thisandagain%2Fsentiment/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thisandagain%2Fsentiment/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thisandagain%2Fsentiment/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/thisandagain","download_url":"https://codeload.github.com/thisandagain/sentiment/tar.gz/refs/heads/develop","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254036807,"owners_count":22003651,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["afinn","analysis","javascript","nlp","sentiment","sentiment-analysis"],"created_at":"2024-07-31T15:01:17.434Z","updated_at":"2025-05-13T22:01:54.005Z","avatar_url":"https://github.com/thisandagain.png","language":"JavaScript","readme":"# sentiment\n### AFINN-based sentiment analysis for Node.js\n\n[![CircleCI](https://circleci.com/gh/thisandagain/sentiment.svg?style=svg)](https://circleci.com/gh/thisandagain/sentiment)\n[![codecov](https://codecov.io/gh/thisandagain/sentiment/branch/develop/graph/badge.svg)](https://codecov.io/gh/thisandagain/sentiment)\n[![Greenkeeper badge](https://badges.greenkeeper.io/thisandagain/sentiment.svg)](https://greenkeeper.io/)\n\nSentiment is a Node.js module that uses the [AFINN-165](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6010) wordlist and [Emoji Sentiment Ranking](http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0144296) to perform [sentiment analysis](http://en.wikipedia.org/wiki/Sentiment_analysis) on arbitrary blocks of input text. Sentiment provides several things:\n\n- Performance (see benchmarks below)\n- The ability to append and overwrite word / value pairs from the AFINN wordlist\n- The ability to easily add support for new languages\n- The ability to easily define custom strategies for negation, emphasis, etc. on a per-language basis\n\n## Table of contents\n\n- [Installation](#installation)\n- [Usage example](#usage-example)\n- [Adding new languages](#adding-new-languages)\n- [Adding and overwriting words](#adding-and-overwriting-words)\n- [API Reference](#api-reference)\n- [How it works](#how-it-works)\n- [Benchmarks](#benchmarks)\n- [Validation](#validation)\n- [Testing](#testing)\n\n## Installation\n```bash\nnpm install sentiment\n```\n\n## Usage example\n```js\nvar Sentiment = require('sentiment');\nvar sentiment = new Sentiment();\nvar result = sentiment.analyze('Cats are stupid.');\nconsole.dir(result);    // Score: -2, Comparative: -0.666\n```\n\n## Adding new languages\nYou can add support for a new language by registering it using the `registerLanguage` method:\n\n```js\nvar frLanguage = {\n  labels: { 'stupide': -2 }\n};\nsentiment.registerLanguage('fr', frLanguage);\n\nvar result = sentiment.analyze('Le chat est stupide.', { language: 'fr' });\nconsole.dir(result);    // Score: -2, Comparative: -0.5\n```\n\nYou can also define custom scoring strategies to handle things like negation and emphasis on a per-language basis:\n```js\nvar frLanguage = {\n  labels: { 'stupide': -2 },\n  scoringStrategy: {\n    apply: function(tokens, cursor, tokenScore) {\n      if (cursor \u003e 0) {\n        var prevtoken = tokens[cursor - 1];\n        if (prevtoken === 'pas') {\n          tokenScore = -tokenScore;\n        }\n      }\n      return tokenScore;\n    }\n  }\n};\nsentiment.registerLanguage('fr', frLanguage);\n\nvar result = sentiment.analyze('Le chat n\\'est pas stupide', { language: 'fr' });\nconsole.dir(result);    // Score: 2, Comparative: 0.4\n```\n\n## Adding and overwriting words\nYou can append and/or overwrite values from AFINN by simply injecting key/value pairs into a sentiment method call:\n```javascript\nvar options = {\n  extras: {\n    'cats': 5,\n    'amazing': 2\n  }\n};\nvar result = sentiment.analyze('Cats are totally amazing!', options);\nconsole.dir(result);    // Score: 7, Comparative: 1.75\n```\n\n## API Reference\n\n#### `var sentiment = new Sentiment([options])`\n\n| Argument | Type       | Required | Description                                                |\n|----------|------------|----------|------------------------------------------------------------|\n| options  | `object`   | `false`  | Configuration options _(no options supported currently)_   |\n\n---\n\n#### `sentiment.analyze(phrase, [options], [callback])`\n\n| Argument | Type       | Required | Description             |\n|----------|------------|----------|-------------------------|\n| phrase   | `string`   | `true`   | Input phrase to analyze |\n| options  | `object`   | `false`  | Options _(see below)_   |\n| callback | `function` | `false`  | If specified, the result is returned using this callback function |\n\n\n`options` object properties:\n\n| Property | Type      | Default | Description                                                   |\n|----------|-----------|---------|---------------------------------------------------------------|\n| language | `string`  | `'en'`  | Language to use for sentiment analysis                        |\n| extras   | `object`  | `{}`    | Set of labels and their associated values to add or overwrite |\n\n---\n\n#### `sentiment.registerLanguage(languageCode, language)`\n\n| Argument     | Type     | Required | Description                                                         |\n|--------------|----------|----------|---------------------------------------------------------------------|\n| languageCode | `string` | `true`   | International two-digit code for the language to add                |\n| language     | `object` | `true`   | Language module (see [Adding new languages](#adding-new-languages)) |\n\n---\n\n## How it works\n### AFINN\nAFINN is a list of words rated for valence with an integer between minus five (negative) and plus five (positive). Sentiment analysis is performed by cross-checking the string tokens (words, emojis) with the AFINN list and getting their respective scores. The comparative score is simply: `sum of each token / number of tokens`. So for example let's take the following:\n\n`I love cats, but I am allergic to them.`\n\nThat string results in the following:\n```javascript\n{\n    score: 1,\n    comparative: 0.1111111111111111,\n    calculation: [ { allergic: -2 }, { love: 3 } ],\n    tokens: [\n        'i',\n        'love',\n        'cats',\n        'but',\n        'i',\n        'am',\n        'allergic',\n        'to',\n        'them'\n    ],\n    words: [\n        'allergic',\n        'love'\n    ],\n    positive: [\n        'love'\n    ],\n    negative: [\n        'allergic'\n    ]\n}\n```\n\n* Returned Objects\n    * __Score__: Score calculated by adding the sentiment values of recognized words.\n    * __Comparative__: Comparative score of the input string.\n    * __Calculation__: An array of words that have a negative or positive valence with their respective AFINN score.\n    * __Token__: All the tokens like words or emojis found in the input string.\n    * __Words__: List of words from input string that were found in AFINN list.\n    * __Positive__: List of positive words in input string that were found in AFINN list.\n    * __Negative__: List of negative words in input string that were found in AFINN list.\n\nIn this case, love has a value of 3, allergic has a value of -2, and the remaining tokens are neutral with a value of 0. Because the string has 9 tokens the resulting comparative score looks like:\n`(3 + -2) / 9 = 0.111111111`\n\nThis approach leaves you with a mid-point of 0 and the upper and lower bounds are constrained to positive and negative 5 respectively (the same as each token! 😸). For example, let's imagine an incredibly \"positive\" string with 200 tokens and where each token has an AFINN score of 5. Our resulting comparative score would look like this:\n\n```\n(max positive score * number of tokens) / number of tokens\n(5 * 200) / 200 = 5\n```\n\n### Tokenization\nTokenization works by splitting the lines of input string, then removing the special characters, and finally splitting it using spaces. This is used to get list of words in the string.\n\n---\n\n## Benchmarks\nA primary motivation for designing `sentiment` was performance. As such, it includes a benchmark script within the test directory that compares it against the [Sentimental](https://github.com/thinkroth/Sentimental) module which provides a nearly equivalent interface and approach. Based on these benchmarks, running on a MacBook Pro with Node v6.9.1, `sentiment` is nearly twice as fast as alternative implementations:\n\n```bash\nsentiment (Latest) x 861,312 ops/sec ±0.87% (89 runs sampled)\nSentimental (1.0.1) x 451,066 ops/sec ±0.99% (92 runs sampled)\n```\n\nTo run the benchmarks yourself:\n```bash\nnpm run test:benchmark\n```\n\n---\n\n## Validation\nWhile the accuracy provided by AFINN is quite good considering it's computational performance (see above) there is always room for improvement. Therefore the `sentiment` module is open to accepting PRs which modify or amend the AFINN / Emoji datasets or implementation given that they improve accuracy and maintain similar performance characteristics. In order to establish this, we test the `sentiment` module against [three labelled datasets provided by UCI](https://archive.ics.uci.edu/ml/datasets/Sentiment+Labelled+Sentences).\n\nTo run the validation tests yourself:\n```bash\nnpm run test:validate\n```\n\n### Rand Accuracy\n```\nAmazon:  0.726\nIMDB:    0.765\nYelp:    0.696\n```\n\n---\n\n## Testing\n```bash\nnpm test\n```\n","funding_links":[],"categories":["JavaScript","Repository","Uncategorized","Open Source Implementations","Libraries","Natural Language Processing"],"sub_categories":["Natural language processing","Uncategorized","NodeJS"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthisandagain%2Fsentiment","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fthisandagain%2Fsentiment","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthisandagain%2Fsentiment/lists"}