简体   繁体   English

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

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

If file.txt contains: 如果file.txt包含:

appple
cheese
cake
tree
pie

Using this: 使用这个:

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

This will only print 1 line from file.txt 这只会从file.txt中打印1行

How would I print 1-2 lines (randomly)? 我如何打印1-2行(随机)?

Example: 例:

first output = apple 第一个输出=苹果
second output = cheesetree 第二输出= cheesetree
third output = piecake 第三输出=饼状
fourth output = cake 第四输出=蛋糕

To produce more than one random number, use random.sample() . 要生成多个随机数,请使用random.sample() You can randomize the sample size: 您可以随机化样本大小:

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

This gives you a list with either 1 or 2 items, picked as a random sample from the input. 这将为您提供一个包含1或2个项目的列表 ,从输入中选择一个随机样本。

Demo: 演示:

>>> 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']

Use str.join() to join the words together, if needed: 如果需要,使用str.join()将单词连接在一起:

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

You have two basic options, depending on (let's say you're in a two-line case) whether you want to pick two random lines , or any random line twice . 你有两个基本选项,取决于(假设你是两行的情况)你是想要选择两个随机行 ,还是两次随机行 That is, whether or not duplicates are allowed. 也就是说,是否允许重复。

If you want to allow duplicates, you need to pick a randint first, and then run the code you already have that many times. 如果要允许重复项,则需要先选择一个randint ,然后多次运行已有的代码。 This is "pick a random line, a random number of times." 这是“随机选择随机数。”

# 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))

In the other case use random.sample and then print all the results. 在另一种情况下,使用random.sample然后打印所有结果。 This is "pick a random number of discrete lines". 这是“选择随机数量的离散线”。

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

Use the appropriate one for your use case! 使用适合您的用例!

Do you want an even probability among all of the outputs? 你想在所有输出中获得均匀概率吗?

Assuming order doesn't matter and n lines in the text file, this means you want to choose from n + n(n-1)/2 = n(n+1)/2 different outcomes. 假设顺序无关紧要,文本文件中有n行,这意味着您要从n + n(n-1)/2 = n(n+1)/2不同的结果中进行选择。 That is (n+1) choose 2 . 那是(n+1) choose 2 If you set an empty value as the additional outcome, then you will get the correct distribution. 如果您将空值设置为其他结果,那么您将获得正确的分配。

Thus: 从而:

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

This is always choosing a random.sample of two, but one of the values could be the empty string that was added. 这总是选择一个2的random.sample ,但其中一个值可能是添加的空字符串。 This will be as if you just choose one single value. 这就好像您只选择一个值。

If you don't actually want an even distribution of all of the possible outcomes, then you would first want to choose if you want 1 or 2, then choose from the list of names accordingly. 如果您实际上并不想要均匀分配所有可能的结果,那么您首先要选择是否需要1或2,然后相应地从名称列表中进行选择。

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

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