2012-08-29 3 views
0

다음 코드를 사용하여 10 개의 임의 줄을 가져 오지만 빈 줄을 픽업합니다. 선택을하는 동안 빈 줄을 제외하기를 원했습니다. 접두어로 *를 사용하여 선택한 행을 표시하려고합니다. 다음번에이 코드는 *로 시작하는 라인을 픽업하지 않을 것입니다.파이썬 빈 행 및 텍스트 표시

import random 
task = 10 
while (task >= 0): 
    lines = open('master.txt').read().splitlines() 
    myline =random.choice(lines)  
    print(myline) 
    task -= 1 
print ('Done!') 
+0

어디에 * 표시를 하시겠습니까? –

+0

@charlieg 선택한 행의 처음부터 선택 중에 빈 행을 삭제하는 것도 좋습니다. – user1582596

답변

1

은 다음 무작위있는 10 개 라인을 선택합니다 ... 오히려 *로 표시보다

lines = lines[10:] 

:

random.shuffle(lines) 
random_lines = lines[:10] 

지금 당신은 당신이 shuffle를 통해 선택 라인을 제거 할 수 있습니다 비어 있지 않고 표시되지 않았습니다. 선택한 선이 인쇄되고 선택한 선이 표시되고 (앞에 *으로 표시됨) 빈 선이 제거되도록 파일이 업데이트됩니다.

import random 
num_lines = 10 

# read the contents of your file into a list 
with open('master.txt', 'r') as f: 
    lines = [L for L in f if L.strip()] # store non-empty lines 

# get the line numbers of lines that are not marked 
candidates = [i for i, L in enumerate(lines) if not L.startswith("*")] 

# if there are too few candidates, simply select all 
if len(candidates) > num_lines: 
    selected = random.sample(candidates, num_lines) 
else: 
    selected = candidates # choose all 

# print the lines that were selected 
print "".join(lines[i] for i in selected) 

# Mark selected lines in original content 
for i in selected: 
    lines[i] = "*%s" % lines[i] # prepend "*" to selected lines 

# overwrite the file with modified content 
with open('master.txt', 'w') as f: 
    f.write("".join(lines)) 
+0

줄을 표시하려면 print (출력)를 사용했지만 출력은 연속 10 줄을 생성합니다. 어쨌든 출력을 줄 단위로 인쇄 할 수 있습니다. 가능하면 빈 줄을 무시하는 대신 삭제할 수 있습니다. – user1582596

+1

선택한 행을 목록에 저장하는 대신 인쇄하도록 코드를 업데이트했습니다. –

+0

이제 빈 줄을 삭제하는 데 필요한 변경 사항을 포함하도록 업데이트하십시오. –

1
import random 
lines = [line 
      for line in open('master.txt').read().splitlines() 
      if line is not ''] 
random.shuffle(lines) 

for line in lines[:10]: 
    print line 
print "Done!" 
1
import random 

task = 10 
with open('master.txt') as input: 
    lines = input.readlines() 
    lines = [line.strip() for line in lines] ## Strip newlines 
    lines = [line for line in lines if line] ## Remove blank 
    selected = random.sample(lines, task) 

for line in selected: 
    print(line) 

print('Done!') 
+0

모든 변수의 이름이 같은'lines'의 이름에 문제가있는 것은''line''의''line''과 같이''lines''과 같이 타이프를 간과하기 쉽다는 것입니다. –

+0

당신은 절대적으로 @Burhan입니다. 하하. 결정된. –

2

은 빈 줄을 제거하려면 :

with open(yourfile) as f: 
    lines = [ line for line in f if line.strip() ] 

당신은 당신의 공상 (예를 들어 if line.strip() and not line.startswith('*'))

에 맞게 지능형리스트의 if 부분에 물건을 수정할 수 있습니다

이제 셔플하고 수행하십시오. 10 :

+0

'remove' 루프가'random.shuffle (lines);과 같지 않습니다; lines = lines [10 :]'? 이미 선을 제자리에 섞어 두었으므로 보존 할 순서가 없습니다. – DSM

+0

@DSM - 네 말이 맞아. 느린 두뇌 하루. – mgilson

0
import random 
task = 10 

#read the lines just once, dont read them again and again 
lines = filter(lambda x: x, open('master.txt').read().splitlines()) 
while (task >= 0 and len(lines)): 
    myline = random.choice(lines) 
    #don't mark the line with *, just remove it from the list 
    lines.remove(myline)  
    print(myline) 
    task -= 1 
print ('Done!')