简体   繁体   English

如何从txt文件中选择python中的随机汽车

[英]How to pick random cars in python from txt file

i've came across this problem that i've been trying to solve: i want to use a txt to randomly pick a car from a txt file but i always get it wrong and i hoped that you could help me here is what i have done so far in this specific part: 我遇到了我一直在试图解决的问题:我想使用txt从txt文件中随机选择一辆汽车,但我总是弄错了,我希望您能在这里为我提供帮助到目前为止,在此特定部分已完成:

import random

if user_input == "1":

  with open("cars.txt", "r") as call_uber:

      for line in call_uber:

          array1 = line.split(" : ")

          print(array1)

the objective is to randomly pick the first name of one of the txt file lines but i just managed to split them 目的是随机选择其中一个txt文件行的名字,但我只是设法将它们拆分

ps: i'm a newbie at this. ps:我是这个新手。

To randomly pick a line, just add random.choice function : 要随机选择一条线,只需添加random.choice函数:

import random

if user_input == "1":

    with open("cars.txt", "r") as call_uber:

        line = random.choice(call_uber.readlines())

        array1 = line.split(" : ")

        print(array1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从txt文件中选取零件,然后使用python复制到另一个文件 - Pick parts from a txt file and copy to another file with python 如何使用 python 从 .txt 文件中提取随机词? - How to extract random words from .txt file using python? 如何让我的 Discord.py 机器人从与我的主代码相同的文件夹中的 .txt 文件中随机选择一条“行”? - How do I make my Discord.py bot pick a random "line" from a .txt file in the same folder as my main code? 如何从 requirements.txt 文件中选择特定版本 - how to pick a particular version from requirement.txt file 如何让我的 discord.py 机器人在 a.txt 文件中随机选择一行并回复消息 - How do i make my discord.py bot pick an random line in a .txt file and reply to a message Python电报Api。 如何从目录中选择随机图像? - Python Telegram Api. How to pick a random image from directory? (Python)如何使python程序从.txt文件中随机取一行? - (Python) How to make python program take a random line from a .txt file? 来自txt(csv)文件的Python图形,共有5列,如何为y轴选择第3列或第4列? - Python graph from txt(csv) file and there are 5 columns, How Can I pick 3rd or 4th columns for y axis? 从列表中随机选择Python,而无需先前选择 - Python random pick from list without previous pick 从.txt文件中选择随机分数并找到它们的平均值(Python) - Selecting random scores from a .txt file and finding their average (Python)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM