HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

French animal generator

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
frenchanimalgenerator

Problem

I'm learning Python. I'm making a random animal generator, from 5 txt files. Each file is a list of words for respectively the specie of the animal, an adjective, an origin, and a bodypart with a color. Not all may appear in the description. I also wanted it to be arithmogrammatic. Here is my code, I know it can be improved, but how ?

import time
import random
z=5
nom=[line.strip() for line in open("ani_nom.txt").readlines()]
adj=[line.strip() for line in open("ani_adj.txt").readlines()]
ori=[line.strip() for line in open("ani_ori.txt").readlines()]
cor=[line.strip() for line in open("ani_cor.txt").readlines()]
cou=[line.strip() for line in open("ani_cou.txt").readlines()]

for w in range (120):
    z=random.randint(1,100)
    Inom=[x for x in nom if len (x) == z ]
    Iadj=[x for x in adj if len (x) == z ]
    Iori=[x for x in ori if len (x) == z ]
    Icor=[x for x in cor if len (x) == z-2 ]
    Icou=[x for x in cou if len (x) == z ]
    try:
            name = random.choice(Inom)
            adje = random.choice(Iadj)
            orig = random.choice(Iori)
            corp = random.choice(Icor)
            coul = random.choice(Icou)
    except IndexError :
        continue
    r = random.randint(1,5)
    print ""
    if r == 0:
        print name      
    elif r == 1:
        print name
        print orig
    elif r == 2:
        print name
        print "a " + corp
        print coul  
    elif r == 3:
        print name
        print adje
        print "a " + corp
        print coul
    elif r == 4:
        print name
        print orig
        print "a " + corp
        print coul
    elif r == 5:
        print name
        print adje
        print orig
        print "a " + corp
        print coul


The quite chaotic results look like this :

```
gecko
d'ete

merles
musque
d'Iran
a tete
Prasin

moucheron
d'Espagne

foulque
pelerin
d'hiver
a duvet
Abricot

crocodile
du Canada
a griffes
Malachite

sphecides
de bassan
a remiges
Framboise

okapi
a pic
Saf

Solution

Use classes

You should consider making animals a class, since you intend to make many of them that all have the same types of characteristics. This is exactly what classes are good for. I've taken the liberty of creating a characteristics dictionary for easy characteristic assignment using the data read from files
Don't repeat yourself

You do most things 5 times in a row (one for each characteristic). You can avoid this in most situations. For reading data, you can stuff each set of characteristics into one element of a dictionary. For assigning characteristics, you can randomly select one item from each element of that dictionary.

Here's a crack at your code, revised:

import random

documents = [
    "ani_nom.txt",
    "ani_adj.txt",
    "ani_ori.txt",
    "ani_cor.txt",
    "ani_cou.txt"
    ]

data = {}

for document in documents:
    try:
        data.update({document.split(".")[0]: [line.strip() for line in open(document)]})
    finally:
        close(document)

class Animal(object):
    def __init__(self):
        self.characteristics = dict(
            ani_nom=None,
            ani_adj=None,
            ani_ori=None,
            ani_cor=None,
            ani_cou=None
        )

    def assign_all_characteristics(self):
        for characteristic in self.characteristics:
            self.characteristics[characteristic] = random.choice(data[characteristic])

    def print_random_characteristics(self):
        num_to_print = random.randint(1, 5)
        characteristics_to_print = list(self.characteristics.values())
        print "\n".join(characteristics_to_print[:num_to_print])

number_of_animals = 120
for _ in range(number_of_animals):
    animal = Animal()
    animal.assign_all_characteristics()
    animal.print_random_characteristics()

Code Snippets

import random

documents = [
    "ani_nom.txt",
    "ani_adj.txt",
    "ani_ori.txt",
    "ani_cor.txt",
    "ani_cou.txt"
    ]

data = {}

for document in documents:
    try:
        data.update({document.split(".")[0]: [line.strip() for line in open(document)]})
    finally:
        close(document)


class Animal(object):
    def __init__(self):
        self.characteristics = dict(
            ani_nom=None,
            ani_adj=None,
            ani_ori=None,
            ani_cor=None,
            ani_cou=None
        )

    def assign_all_characteristics(self):
        for characteristic in self.characteristics:
            self.characteristics[characteristic] = random.choice(data[characteristic])

    def print_random_characteristics(self):
        num_to_print = random.randint(1, 5)
        characteristics_to_print = list(self.characteristics.values())
        print "\n".join(characteristics_to_print[:num_to_print])

number_of_animals = 120
for _ in range(number_of_animals):
    animal = Animal()
    animal.assign_all_characteristics()
    animal.print_random_characteristics()

Context

StackExchange Code Review Q#133482, answer score: 12

Revisions (0)

No revisions yet.