2011-09-13 9 views
1

'이름'이라는 .txt 파일에서 "john, jack, daniels, whisky, susan, alex"와 같은 이름 목록을 갖고 싶습니다.파이썬 도움말 --- 텍스트 파일의 임의 이름 선택

이제이 파일을 '스크립트'로 가져 와서 가져 오기 임의 모듈을 사용하고 싶습니다.

이 내가 가진 것입니다 : 대신 name = (xxxxxxxxxxxxx) 갖는

import random 

name = ("jay" , "luis" , "bob" , "sofi", "susan") 

x = random.sample(name,input("please enter the number of volunteers needed")) 
print x 

을, 나는 이름 = .txt 파일을 갖고 싶어.

언제나 이름을 변경하고 싶습니다. 단지 .txt 파일로 변경할 수 있습니다.

나는 학교 자원 봉사자 클럽을위한 프로그램을 만들려고 노력하고있어, 선택한 자원 봉사자의 수는 무작위이며 편견이 없습니다. 그렇게하면 모든 사람들이 공정한 기회를 갖게됩니다. :]

+3

에 오신 것을 환영합니다! 당신은 정말로 몇 가지 기본적인 파이썬 튜토리얼 * (예 : http://www.penzilla.net/tutorials/python/fileio/) * 파일을 열어 그것을 읽고 ","로 줄을 나눌 필요가 있습니다. 또는 읽으십시오 : http://stackoverflow.com/questions/6136154/csv-file-read-in-python –

답변

1

당신은 단순히 선으로 구분 된 이름을 가진 텍스트 파일을 채울 수 : 당신의 name = ... 라인 대신에 당신이 갈 수 있어야한다

with open('names.txt') as f: 
    names = f.read().splitlines() 
3
file = open('myFile.txt', 'r') 
names = file.read().split(',') 
file.close() 

사용.

파일 읽기 및 쓰기에 대한 자세한 내용은 Python here에서 읽을 수 있습니다.

파일에 쉼표로 분리 된 목록이 있다고 가정했음을 유의하십시오. 각각의 이름을 별도의 줄에 넣고 names = file.readlines()을 대신 입력 할 수도 있습니다.

0

한 줄에 하나씩, names.txt에 이름 목록을 가정 (그리고 당신은 거기에서 일억 이름이없는 것을) : 파이썬

import random 
number_of_volunteers = 4 
print random.sample([n[:-1] for n in open("./names.txt").readlines()], number_of_volunteers) 
2

오신 것을 환영합니다 : -]

방법에 대한 이 같은?

import random 
fid = open('names.txt', 'r') 
names = fid.readlines() 

number_needed = raw_input('please enter the number of volunteers needed: ') 

print random.sample(names, int(number_needed)) 
0

장소 :

$ cat rand_nms.txt 
jay 
luis 
bob 
sofi 
다음

:

import random 

contents=[] 

with open("rand_nms.txt") as rnd: 
    for line in rnd: 
     line=line.strip() 
     contents.append(line) 

print contents 
print "random name:", contents[random.randint(0,len(contents)-1)] 

결과 : 스택 오버플로

['jay', 'luis', 'bob', 'sofi', 'susan'] 
random name: luis