The process of making Python code object-oriented and improving it

The process of making Python code object-oriented and improving it

You can do object-oriented programming in Python. I would like to make use of it to improve convenience and readability. This time, I recorded the process of making a spaghetti code program that I created object-oriented.

What is object orientation?

"Object-Oriented" is, quite roughly speaking, ** an object, a collection of data, Propaties, and related actions (Behavior, Method). The idea is to put it together in a pack. Applying this idea to programming requires two processes: Object-Oriented Analysis (OOA) and Object-Oriented Design (OOD).

Object-oriented analysis

Here, let's assume that the other day Ethical Baysean Classifier is object-oriented. The content of this program is basically a naive Bayes classifier. After reading the text, it is trained and the text entered by the user is labeled. Let's start with an object-oriented analysis of this program. What you should do at the "object-oriented analysis" stage is to ** understand the mechanics and structure of the system and interpret it as the behavior of a series of objects **. In this case, it can be understood that the object itself is only one "classifier", the learning text / judgment text is data, and the process of learning / judgment is an operation.

Object-oriented design

Once you understand how the program works with object-oriented analysis, it's time to define the ** requirements **. There is only one "classifier" for the object, the data can be narrowed down to four types of learning text, judgment text, each label, and shaped data after learning, and the operation can be narrowed down to three types: input, learning, and judgment. ..

Improved code

Ethical_Baysean_Classifier-OOP.ipynb


import numpy as np
import matplotlib.pyplot as plt
from textblob import TextBlob
from textblob.classifiers import NaiveBayesClassifier 

class Classifier():
    
    def __init__(self):
        self.act_pos = []
        self.etc_pos = []
        self.etc_neg = []
        self.etc_user = []
        self.etc_user_label = []
        self.etc_user_label2 = []
        self.trained1 = []
        self.trained2 = []
    
        print("Classifier has initiated.")
    
    
    def input(self):
        with open("analysed/actual_statement_pos.txt","r", encoding="utf8", errors='ignore')as f:
            entire_txt = f.read()
            self.act_pos = entire_txt.splitlines()
            print("Text lines =", len(self.act_pos))    
        with open("analysed/ethical_statement_pos.txt","r", encoding="utf8", errors='ignore')as f:
            entire_txt2 = f.read()
            self.etc_pos = entire_txt2.splitlines()
            print("Text lines =", len(self.etc_pos)) 
        with open("analysed/ethical_statement_neg.txt","r", encoding="utf8", errors='ignore')as f:
            entire_txt3 = f.read()
            self.etc_neg = entire_txt3.splitlines()
            print("Text lines =", len(self.etc_neg))
        with open("analysed/ethical_statement_user.txt","r", encoding="utf8", errors='ignore')as f:
            entire_txt4 = f.read()
            self.etc_user = entire_txt4.splitlines()
            print("Text lines =", len(self.etc_user))
        
        
    def train(self):
        for i,item in enumerate(self.act_pos):
            self.trained1 = [ 
                (self.act_pos[i], "act"), 
                (self.etc_pos[i], "etc"), 
            ] 
        for i,item in enumerate(self.act_pos):
            self.trained2 = [ 
                (self.etc_pos[i], "etc_pos"), 
                (self.etc_neg[i], "etc_neg"), 
            ] 
        print("\n Classifier has trained for Actual/Ethical,Correct/Wrong distinction.")
        
        
    def classify(self):
        trained1 = self.trained1
        cl = NaiveBayesClassifier(trained1)
        
        print("\n Actual/Ethical distinction")
        
        for i,item in enumerate(self.act_pos):
            self.etc_user_label.append(cl.classify(self.etc_user[i]))
            print(self.etc_user[i],"<<- Text | Classified ->> ", self.etc_user_label[i])
            
            
        trained2 = self.trained2
        cl = NaiveBayesClassifier(trained2)
        
        print("\n Correct/Wrong distinction")
        
        for i,item in enumerate(self.act_pos):
            self.etc_user_label2.append(cl.classify(self.etc_user[i]))
            print(self.etc_user[i],"<<- Text | Classified ->> ", self.etc_user_label2[i])
            
clsf = Classifier()
clsf.input()
clsf.train()
clsf.classify()

Execution result

Classifier has initiated. Text lines = 10 Text lines = 10 Text lines = 10 Text lines = 10

Classifier has trained for Actual/Ethical,Correct/Wrong distinction.

Actual/Ethical distinction We must not be late. <<- Text | Classified ->> etc We must fight against odds. <<- Text | Classified ->> etc We must take the evil with the good. <<- Text | Classified ->> etc We must consider the gravity of the situation. <<- Text | Classified ->> etc We must have high ideals. <<- Text | Classified ->> etc We must keep calm. <<- Text | Classified ->> etc We must try to find him, <<- Text | Classified ->> etc We must not forget that day. <<- Text | Classified ->> etc We must protect that. <<- Text | Classified ->> etc We must always provide against accidents. <<- Text | Classified ->> etc

Correct/Wrong distinction We must not be late. <<- Text | Classified ->> etc_neg We must fight against odds. <<- Text | Classified ->> etc_pos We must take the evil with the good. <<- Text | Classified ->> etc_pos We must consider the gravity of the situation. <<- Text | Classified ->> etc_pos We must have high ideals. <<- Text | Classified ->> etc_pos We must keep calm. <<- Text | Classified ->> etc_pos We must try to find him, <<- Text | Classified ->> etc_pos We must not forget that day. <<- Text | Classified ->> etc_neg We must protect that. <<- Text | Classified ->> etc_pos We must always provide against accidents. <<- Text | Classified ->> etc_pos

You can run any object-oriented program with just four lines of code.

Recommended Posts

The process of making Python code object-oriented and improving it
The process of installing Atom and getting Python running
The story of Python and the story of NaN
The result of making a map album of Italy honeymoon in Python and sharing it
[PEP8] Take over the Python source code and write it neatly
Convert the result of python optparse to dict and utilize it
Installation of Visual studio code and installation of python
The story of making Python an exe
[Python3] Rewrite the code object of the function
Set the process name of the Python program
[Python] Get the character code of the file
Process the gzip file UNLOADed with Redshift with Python of Lambda, gzip it again and upload it to S3
Summary of the differences between PHP and Python
The answer of "1/2" is different between python2 and 3
Specifying the range of ruby and python arrays
Send Gmail at the end of the process [Python]
[Python] Read the source code of Bottle Part 1
Links and memos of Python character code strings
Code for checking the operation of Python Matplotlib
List of Python code to move and remember
Convert the character code of the file with Python3
About the * (asterisk) argument of python (and itertools.starmap)
A discussion of the strengths and weaknesses of Python
What I investigated in the process of expressing (schematicizing) containers in a nested frame with Jupyter and making it
the zen of Python
The story of Python without increment and decrement operators.
Automatically determine and process the encoding of the text file
Python --Explanation and usage summary of the top 24 packages
Visualize the range of interpolation and extrapolation with python
I checked out the versions of Blender and Python
[Python3] Take a screenshot of a web page on the server and crop it further
Check the processing time and the number of calls for each process in python (cProfile)
Towards the retirement of Python2
[Python] Heron's formula functionalization and calculation of the maximum area
About the ease of Python
Explain the code of Tensorflow_in_ROS
The story of Python and the story of NaN
Python nan check
[python] plot the values ​​before and after the conversion of yeojohnson conversion
Return the image data with Flask of Python and draw it to the canvas element of HTML
2.x, 3.x character code of python
[Python] I installed the game from pip and played it
Let's statically check and format the code of E2E automatic test written in Python [VS Code]
Debug by attaching to the Python process of the SSH destination
The websocket of toio (nodejs) and python / websocket do not connect.
I want to know the features of Python and pip
Object-oriented in C: Refactored "○ ✕ game" and ported it to Python
[Tips] Problems and solutions in the development of python + kivy
About the features of Python
Source installation and installation of Python
Play with the password mechanism of GitHub Webhook and Python
Overview of Python virtual environment and how to create it
The Power of Pandas: Python
I tried to remodel the code of Python beginner (junior high school student) into object-oriented crunchy
Find the white Christmas rate by prefecture with Python and map it to a map of Japan
[Python] The role of the asterisk in front of the variable. Divide the input value and assign it to a variable
Count the number of Thai and Arabic characters well in Python
Note: Get the first and last items of Python OrderedDict non-destructively
Let's measure the test coverage of pushed python code on GitHub.
Scraping the schedule of Hinatazaka46 and reflecting it in Google Calendar
[Introduction to Python] I compared the naming conventions of C # and Python.
First python ② Try to write code while examining the features of python