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!')
4

5 回答 5

2

摆脱空行:

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

您可以修改if列表理解部分中的内容以适合您的喜好(if line.strip() and not line.startswith('*')例如)

现在洗牌并取 10:

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

现在您可以通过以下方式删除您选择的行shuffle

lines = lines[10:]

而不是用*...标记

于 2012-08-29T14:44:36.740 回答
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!"
于 2012-08-29T14:41:01.283 回答
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!')
于 2012-08-29T14:42:58.853 回答
1

下面将随机选择10行非空且未标记的行。打印出所选行并更新文件,以便标记所选行(以 开头*)并删除空行。

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))
于 2012-08-29T14:52:00.370 回答
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!')
于 2012-08-29T14:50:02.843 回答