hissroth
hissroth

Reputation: 251

How to get a specific word from an array?

I've created a program that open a text file and read it's content. My goal is to sort a random value from the line of the word asking by the user. My text file is formatted this way.

name = Jojo, Yomi, Tata, Toto;
age = 14, 45, 1, 5;
century = 15th, 4th;
power = fire, wind, dirt;
breed = human, elf;
size = 1m, 4m, 2m;
ability = smart, fast;   

And with my code I'm stocking all the data in this way

[['name = Jojo, Yomi, Tata, Toto', '\n'], ['age = 14, 45, 1, 5', '\n'], ['century = 15th, 4th', '\n'], ['power = fire, wind, dirt', '\n'], ['breed = human, elf', '\n'], ['size = 1m, 4m, 2m', '\n'], ['ability = smart, fast', '   ']]

But my issue is that I'm asking the user in input how many categories from the file he wants, so after that I stock the user input in a list. After this I want to check in the file where his words are to be able to sort a random word from this specific string. And I don't know how to do the "check where the word is" in the file formatted as I said earlier it's searching a word from a list in another list.

for example if in input he ask for 3 values, let's say name, century, power, the program will sort as a random value Yomi, 5, dirt.

Here is the code I've made for the moment.

import sys 
import time

def read_file():
    data = []

    if len(sys.argv) != 2:
        print("Error on the input of argument.")
        print("Missing the txt file.")
        sys.exit(1)
    with open(sys.argv[1], "r") as f:
        lines = f.readlines()
        for line in lines:
            data.append(line.split(";"))
    return(data)

def ask_input():
    loop = input("How many random data you want ?\n")
    loop = int(loop)
    stock = []

    for i in range(loop):
        ask = input("What category do you want ?\n")
        stock.append(ask)
        i += 1
    return(stock)

def usage():
    print("Hi and welcome on my random generator.")
    print("Then you will have to enter the amount of data you want.")
    print("You will have to enter your data one by one until you reach the number asked before.\n")
    time.sleep(3)
    print("Would you like to start")
    should_continue = input("'Yes' or 'No' ?\n")
    if "Yes" in should_continue:
        ask_input()
    if "No" in should_continue:
        print("Ok hope you enjoyed, goodbye !\n")
        sys.exit(1)

if __name__ == "__main__":
    read_file()

My over question is how to make this program from a python file to an executable file without using py file.py for windows etc ?

Upvotes: 0

Views: 306

Answers (3)

DavidE
DavidE

Reputation: 91

I feel like your job would be much easier if your data/text file was in JSON form. You then would have keys and data related to these keys.

for example, you could ask the user :

ask = input("What category do you want ?\n")

You then can check if ask is a key like this:

if ask in data.keys():
...

Or selecting randomly from :

data[ask]

My best guess is to use dictionaries or convert somehow your data into dictionaries

Upvotes: 1

Frank
Frank

Reputation: 2029

Would this be a good solution for you?

It would be a little more accessible because you get a dict of lists. You can see the output of your example at the bottom. I stripped the ; and newline but it would be no problem to keep them.

import sys 
import time

def read_file():
    data = []

    if len(sys.argv) != 2:
        print("Error on the input of argument.")
        print("Missing the txt file.")
        sys.exit(1)
    with open(sys.argv[1], "r") as f:
        lines = f.readlines()
        line_dict = {}
        for line in lines:
            key, value = line.split('=')
            line_dict[key] = value.strip().strip(';').split(', ')
    return(line_dict)

if __name__ == "__main__":
    read_file()
# {'name ': [' Jojo', 'Yomi', 'Tata', 'Toto'], 'age ': [' 14', '45', '1', '5'], 'century ': [' 15th', '4th'], 'power ': [' fire', 'wind', 'dirt'], 'breed ': [' human', 'elf'], 'size ': [' 1m', '4m', '2m'], 'ability ': [' smart', 'fast;  ']}

Upvotes: 0

Sebastien Hoarau
Sebastien Hoarau

Reputation: 76

Correira rights on this point: your datas structure is not accurate. A dictionary seems better:

def read_file(filename):
    d_datas = {}
    with open(filename) as f:
        for ligne in f:
            cat, datas = ligne.strip().strip(';').split(' = ')
            d_datas[cat] = datas.split(', ')
    return d_datas



if __name__ == '__main__':
    if len(sys.argv) < 2:
        raise Exception('Missing filename')
    d_datas = read_file(sys.argv[1])
    print(d_datas)

giving this:

{'name': ['Jojo', 'Yomi', 'Tata', 'Toto'], 
 'age': ['14', '45', '1', '5'], 
 'century': ['15th', '4th'], 
 'power': ['fire', 'wind', 'dirt'], 
 'breed': ['human', 'elf'], 
 'size': ['1m', '4m', '2m'], 
 'ability': ['smart', 'fast']}

Upvotes: 2

Related Questions