首页 > 解决方案 > 如何从数组中获取特定单词?

问题描述

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

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

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

标签: pythonpython-3.x

解决方案


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

推荐阅读