繁体   English   中英

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

[英]Python - Print random number of lines from file

如果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
第三输出=饼状
第四输出=蛋糕

要生成多个随机数,请使用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'

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

如果要允许重复项,则需要先选择一个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)

使用适合您的用例!

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

假设顺序无关紧要,文本文件中有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))

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM