은 다음 무작위있는 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))
어디에 * 표시를 하시겠습니까? –
@charlieg 선택한 행의 처음부터 선택 중에 빈 행을 삭제하는 것도 좋습니다. – user1582596