~~ Understand the emotions of people who tremble because they want to meet ~~
Sentiment analysis from the lyrics Is it a bright song? Is it a sad song? I want to judge.
It would be great if we could perform ambiguous searches such as bright songs and sad songs on music distribution services. This year is a difficult year and it's not good, so I'm doing my best listening to bright songs
COTOHA API Python 3.8.1
The following has already been categorized in RecoChoku, so I selected a song from them as my hobby.
Does the cactus stop dancing in sentiment analysis? I was allowed to reference.
top/
 ├ file/
 │ ├ input.txt   (Lyrics to analyze)
 │ └ output.csv (Output result)
 ├ config.ini
  └ cotoha_sentiment.py
cotoha_sentiment.py
# -*- coding:utf-8 -*-
import os
import urllib.request
import json
import configparser
import codecs
import csv
class CotohaApi:
    def __init__(self, client_id, client_secret, developer_api_base_url, access_token_publish_url):
        self.client_id = client_id
        self.client_secret = client_secret
        self.developer_api_base_url = developer_api_base_url
        self.access_token_publish_url = access_token_publish_url
        self.getAccessToken()
    def getAccessToken(self):
        url = self.access_token_publish_url
        headers={
            "Content-Type": "application/json;charset=UTF-8"
        }
        data = {
            "grantType": "client_credentials",
            "clientId": self.client_id,
            "clientSecret": self.client_secret
        }
        data = json.dumps(data).encode()
        req = urllib.request.Request(url, data, headers)
        res = urllib.request.urlopen(req)
        res_body = res.read()
        res_body = json.loads(res_body)
        self.access_token = res_body["access_token"]
    #Sentiment analysis API
    def sentiment(self, sentence):
        url = self.developer_api_base_url + "nlp/v1/sentiment"
        headers={
            "Authorization": "Bearer " + self.access_token,
            "Content-Type": "application/json;charset=UTF-8",
        }
        data = {
            "sentence": sentence
        }
        data = json.dumps(data).encode()
        req = urllib.request.Request(url, data, headers)
        try:
            res = urllib.request.urlopen(req)
        except urllib.request.HTTPError as e:
            print ("<Error> " + e.reason)
        res_body = res.read()
        res_body = json.loads(res_body)
        return res_body
if __name__ == '__main__':
    APP_ROOT = os.path.dirname(os.path.abspath( __file__)) + "/"
    # config.Get ini value
    config = configparser.ConfigParser()
    config.read(APP_ROOT + "config.ini")
    CLIENT_ID = config.get("COTOHA API", "Developer Client id")
    CLIENT_SECRET = config.get("COTOHA API", "Developer Client secret")
    DEVELOPER_API_BASE_URL = config.get("COTOHA API", "Developer API Base URL")
    ACCESS_TOKEN_PUBLISH_URL = config.get("COTOHA API", "Access Token Publish URL")
    cotoha_api = CotohaApi(CLIENT_ID, CLIENT_SECRET, DEVELOPER_API_BASE_URL, ACCESS_TOKEN_PUBLISH_URL)
       # file/infile.Get analysis target sentence from txt
    checkpath = 'file/input.txt'
    song_data = open(checkpath, "r", encoding='utf-8')
    output_file = open('file/output.csv', 'w')
    writer = csv.writer(output_file, lineterminator='\n') #Line feed code (\n) is specified
    sentence = song_data.readline()
    while sentence:
        print(sentence.strip())
        #API execution
        result = cotoha_api.sentiment(sentence)
        score = result["result"]["score"]
        print(score)
        sentiment = result["result"]["sentiment"]
        print(sentiment)
        one_row = [score,sentiment]
        writer.writerow(one_row)  #pass list
        sentence = song_data.readline()
    song_data.close()
    output_file.close()
    
I want to see you, I want to see you, I tremble
Feel as far as you think
Tell me again, even if it's a lie
Like that day"I love you"What ...
…
 
  It wasn't as negative as I expected
 It wasn't as negative as I expected
Tomorrow, I can love you more than today
I still like it so much, but I can't put it into words
The days you gave me piled up and passed away The days when two people walked "trajectory"
…
 
  
Pretty positive song
If there is a faint light in your tears
In front of you
I'm talking about warming up
…
 
  If anything, there are many negative lyrics
 If anything, there are many negative lyrics
SPYAIR 「BEAUTIFUL DAYS」
I can change it more positively Let's believe that way
If someone laughs at you, I won't laugh
A new start Anyone can shine
With anxiety & expectations Oh Try yourself
…
 
  I thought it was a pretty positive song for me
## Ken Hirai "Non-Fiction"
 I thought it was a pretty positive song for me
## Ken Hirai "Non-Fiction"
 Many of the dreams I have drawn do not come true
I hate myself when I envy good people
Some nights are likely to be crushed by a light sleep
…
 
  
Well negative
Goodbye stuck in the back of my throat
I said thank you like coughing
The next word is even if you look for a pocket somewhere
…
 
  Well-balanced
 Well-balanced
~~ I can't understand the emotions of people who tremble because they want to meet ~~
This sentiment analysis was done line by line, I think that the results are biased due to the order of the words. I think that more accurate results will be obtained if the granularity of the lyrics to be analyzed is finer, so I will try it if I have time.
Recommended Posts