从Python中的文件中读取许多随机行
你的要求是有点模糊,所以这里的另一种略有不同的方法(灵感,如果没有别的):
from random import random
lines = [line for line in open("/some/file") if random() >= .5]
与其他解决方案相比,行数变化较小(分布在总行数的一半左右),但每行选择的概率为50%,并且只需要传递一个文件。
+1我很喜欢这个解决方案。 – aaronasterling 2010-11-05 12:39:00
'random.random()> .5'在这里有什么意义? – user225312 2010-11-05 12:40:43
'random()'返回一个0到1之间的随机数,并且分布均匀。 random()> .5'将在一半的时间±正态分布,即每条线以50%的概率被选择。 – SimonJ 2010-11-05 12:44:13
import os,random
def getrandfromMem(filename) :
fd = file(filename,'rb')
l = fd.readlines()
pos = random.randint(0,len(l))
fd.close()
return (pos,l[pos])
def getrandomline2(filename) :
filesize = os.stat(filename)[6]
if filesize < 4096 : # Seek may not be very useful
return getrandfromMem(filename)
fd = file(filename,'rb')
for _ in range(10) : # Try 10 times
pos = random.randint(0,filesize)
fd.seek(pos)
fd.readline() # Read and ignore
line = fd.readline()
if line != '' :
break
if line != '' :
return (pos,line)
else :
getrandfromMem(filename)
getrandomline2("shaks12.txt")
你也可以检查 http://www.bryceboe.com/2009/03/23/random-lines-from-a-file/ – 2010-11-05 12:25:57
假设偏移总是在文件的开头:
import random
lines = file('/your/file').read().splitlines()
n_lines = random.randrange(len(lines))
random_lines = lines[:n_lines]
注意,这将整个文件读入内存中。
这将只会返回前n行。 – aaronasterling 2010-11-05 12:38:07
import linecache
import random
import sys
# number of line to get.
NUM_LINES_GET = 5
# Get number of line in the file.
with open('file_name') as f:
number_of_lines = len(f.readlines())
if NUM_LINES_GET > number_of_lines:
print "are you crazy !!!!"
sys.exit(1)
# Choose a random number of a line from the file.
for i in random.sample(range(1, number_of_lines+1), NUM_LINES_GET)
print linecache.getline('file_name', i)
linecache.clearcache()
这不是随机的行数。 – aaronasterling 2010-11-05 12:36:24
@aaronasterling:呃?也许我没有很好地理解这个问题,但他要求随机数字的行不是随机行的数字吗? – mouad 2010-11-05 12:39:06
你总是会返回5行,而5不是很随意:)但我同意,问题很模糊。 – SimonJ 2010-11-05 12:41:44
为了得到多条线路从您的文件进行随机你可以做类似如下:
import random
with open('file.txt') as f:
lines = random.sample(f.readlines(),5)
上面的例子返回5行,但你可以很容易地改变你的需要数量。您也可以将其更改为randint()
以获得随机数量的行以及多个随机行,但您必须确保样本大小不超过文件中的行数。根据您的输入,这可能是微不足道的,或者更复杂一点。
请注意,行可能以lines
的顺序出现在文件中。
什么是“随机数行”的范围?偏移量也是随机的吗? – 2010-11-05 12:27:39
“许多随机线条”和“随机数线条”是完全不同的东西。 – 2010-11-05 13:08:45