In: Computer Science
PYTHON-- trying to teach myself how to create new classes. The Bird class will read a file that has a list of species and will write to another file with the species and # of occurrences . use __lt__ to compare species and use #comments to explain the def methods in the class
example of input file:
blackbird
canary
hummingbird
canary
hummingbird
canary
output file:
Blackbird,1 Hummingbird,2 Canary,3
class Birds:
    
    #do i need count in init?
    def __init__(self, species, count):
        self.species = species
        self.count = int(count)
    
    def __str__(self):
        return f" {self.species}, {self.count}"
    
    def __repr__(self):
       
    
    def __eq__(self, other):
        
    
    def __lt__(self, other):
        return self.species < other.species
word_freq = []
with open('bird_observations_small.txt', 'r') as input_file:
    for line in input_file:
        data = line.strip().split(',')
        x = Birds(data[0], data[1])
        if x not in word_freq:
            word_freq.append(x)
            
with open('sorted_species.csv', 'w') as output_file:
    for i in word_freq:
        output_file.write(f"{i.species},{i.count}\n")
class Birds:
    count = 0  #intial bird count is 0
    def __init__(self, species):
        self.species = species #initialize it with a string that is the bird name
    
    def __count__(self):
        self.count = self.count + 1         #increaces 1 everytime it gets called
    def __compare__(self, other):
        if self.species == other: #compares self.name with the string passed to it
            return True
        else:
            return False
    def getSpeciesName(self): #getname
        return self.species
    def getCount(self):   #getcount
        return self.count
blackbird = Birds("blackbird") #objects created
canary = Birds("canary")
hummingbird = Birds("hummingbird")
#you can use an array of bird to make things simple and robust
with open('test', 'r') as input_file: #comparision
    for line in input_file:
        line = line.strip() 
        if blackbird.__compare__(line):
            blackbird.__count__()
        if canary.__compare__(line):
            canary.__count__()
        if hummingbird.__compare__(line):
            hummingbird.__count__()
            
with open('out', 'w') as output_file:
    output_file.write(f"{blackbird.getSpeciesName()},{blackbird.getCount()}\n")
    output_file.write(f"{canary.getSpeciesName()},{canary.getCount()}\n")
    output_file.write(f"{hummingbird.getSpeciesName()},{hummingbird.getCount()}\n")