如何从数组中获取特定单词?

时间:2019-09-07 12:47:48

标签: python python-3.x

我创建了一个程序,该程序可以打开文本文件并读取其内容。我的目标是从用户询问的单词行中排序一个随机值。我的文本文件采用这种格式。

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;   

通过我的代码,我以这种方式存储所有数据

[['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', '   ']]

但是我的问题是我要在输入中询问用户他想要的文件中有多少个类别,因此之后我将用户输入存储在一个列表中。在此之后,我要在文件中检入他的单词,以便能够从该特定字符串中对随机单词进行排序。而且我不知道如何在格式化文件中执行“检查单词在哪里”,正如我之前所说的,它是从另一个列表中的一个列表中搜索单词。

例如,如果他在输入中要求输入3个值(例如name, century, power),则程序将排序为随机值Yomi, 5, dirt

这是我目前编写的代码。

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()

我的首要问题是如何在不为Windows等使用py file.py的情况下将该程序从python文件转换为可执行文件?

3 个答案:

答案 0 :(得分:2)

Correira在这一点上的权利:您的数据结构不正确。字典似乎更好:

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)

为此:

{'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']}

答案 1 :(得分:1)

如果您的数据/文本文件采用JSON格式,我觉得您的工作会容易得多。 然后,您将拥有密钥和与这些密钥相关的数据。

例如,您可以问用户:

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

然后您可以检查问是否是这样的键:

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

或从中随机选择:

data[ask]

我最好的猜测是使用词典或以某种方式将您的数据转换为词典

答案 2 :(得分:0)

这对您来说是一个好的解决方案吗?

它会更容易访问,因为您会得到列表的字典。 您可以在底部看到示例的输出。 我剥掉了;和换行符,但是保留它们就没问题。

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;  ']}