Python帮助--->从文本文件中随机选择名称
我想在名为“names”的 .txt 文件中列出“john、jack、daniels、whisky、susan、alex”等姓名列表。
现在,我想将该文件导入到我的“脚本”中并使用导入随机模块。
这就是我所拥有的:
import random
name = ( "jay" , "luis" , "bob" , "sofi", "susan" )
x = random.sample(name,input( "please enter the number of volunteers needed" ))
print x
我想要 name = .txt 文件,而不是 name = ( xxxxxxxxxxxxx )
。
每次我想更改名称时,我都可以在 .txt 文件中更改它。
我正在尝试为我的学校志愿者俱乐部制定一个计划,因此选择的志愿者数量是随机的并且没有偏见。这样每个人都有公平的机会。 :]
I want to have a list of names such as "john, jack, daniels, whisky, susan, alex" in a .txt file called 'names'.
Now, I want to import that file into my 'script' and use the import random module.
This is what I have:
import random
name = ( "jay" , "luis" , "bob" , "sofi", "susan" )
x = random.sample(name,input( "please enter the number of volunteers needed" ))
print x
instead of having name = ( xxxxxxxxxxxxx )
, I want to have name = .txt file.
Everytime i want to change the names I can just change it in the .txt file.
I'm trying to make a program for my schools volunteer club, so the number of volunteers chosen is at random and not biased. That way everyone has a somewhat fair chance. :]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用它代替您的
name = ...
行,您应该可以开始了。您可以在 此处。
请注意,我假设文件中会有一个以逗号分隔的列表。您还可以将每个名称放在单独的行上,然后执行
names = file.readlines()
操作。Use that in place of your
name = ...
line and you should be good to go.You can read more about reading and writing files in Python here.
Note that I assumed you'll have a comma-delimited list in the file. You can also put each name on a separate line and do
names = file.readlines()
instead.欢迎使用 python :-]
这样的东西怎么样?
welcome to python :-]
how about something like this?
您可以简单地用由行分隔的名称填充文本文件:
You could simply fill a text file with names delimited by line:
假设
names.txt
中有一个名称列表,每行一个(并且其中没有一亿个名称):Assuming a list of names in
names.txt
, one per line (and that you don't have a hundred million names in there):地点:
然后:
结果:
Where:
Then:
Result: