Python - 从文件中打印随机行数

时间:2014-06-12 20:32:37

标签: python random

如果file.txt包含:

appple
cheese
cake
tree
pie

使用此:

nameFile = ("/path/to/file.txt")
nameLines = open(nameFile).read().splitlines()
randomName = random.choice(nameLines)

这只会从file.txt

打印1行

我如何打印1-2行(随机)?

实施例

第一个输出=苹果
第二输出= cheesetree
第三输出=馅饼
第四输出=蛋糕

3 个答案:

答案 0 :(得分:4)

要生成多个随机数,请使用random.sample()。您可以随机化样本大小:

randomNames = random.sample(nameLines, random.randint(1, 2))

这为您提供了一个带有1或2个项目的列表,从输入中选择随机样本。

演示:

>>> import random
>>> nameLines = '''\
... apple
... cheese
... cake
... tree
... pie
... '''.splitlines()
>>> random.sample(nameLines, random.randint(1, 2))
['apple', 'cake']
>>> random.sample(nameLines, random.randint(1, 2))
['cheese']

如果需要,使用str.join()将单词连接在一起:

>>> ' '.join(random.sample(nameLines, random.randint(1, 2)))
'pie cake'
>>> ' '.join(random.sample(nameLines, random.randint(1, 2)))
'cake'

答案 1 :(得分:1)

你有两个基本选项,取决于(假设你是两行的情况)你是否要选择两条随机行,或任意一行两次。也就是说,是否允许重复。

如果要允许重复项,则需要先选择randint,然后多次运行已有的代码。这是“随机选择随机数。”

# print one or two random lines: possibly the same line twice!
for i in range(random.randint(1, 2)): # change the upper bound as desired
    print(random.choice(nameLines))

在另一种情况下,使用random.sample然后打印所有结果。这是“选择随机数量的离散线”。

# print one or two distinct elements, chosen at random from nameLines
for line in random.sample(nameLines, random.randint(1, 2)):
    print(line)

根据您的使用情况使用合适的一个!

答案 2 :(得分:1)

你想在所有输出中获得均匀概率吗?

假设订单与文本文件中的n行不重要,这意味着您要从n + n(n-1)/2 = n(n+1)/2个不同的结果中进行选择。那是(n+1) choose 2。如果您将空值设置为附加结果,那么您将获得正确的分配。

因此:

nameFile = ("/path/to/file.txt")
nameLines = open(nameFile).read().splitlines()
nameLines.append("")
randomName = "".join(random.sample(nameLines, 2))

这总是选择两个random.sample,但其中一个值可能是添加的空字符串。这就好像您只选择一个值。

如果您实际上并不想要均匀分配所有可能的结果,那么您首先要选择是否需要1或2,然后相应地从名单中选择。