gpt4 book ai didi

python - 从文件中检索 10 个随机行

转载 作者:太空宇宙 更新时间:2023-11-03 12:21:23 25 4
gpt4 key购买 nike

我有一个 10k 行长的文本文件,我需要构建一个函数,每次从该文件中随机提取 10 行。我已经找到了如何使用 numpy 在 Python 中生成随机数以及如何打开文件,但我不知道如何将它们混合在一起。请帮忙。

最佳答案

如果您知道您的文件正好 10k 那么您可以使用linecache :

import random
import linecache

def random_lines(filename)
idxs = random.sample(range(10000), 10)
return [linecache.getline(filename, i) for i in idxs]

这将返回一个包含 10 行的随机列表,您可以使用这些行进行打印:

for line in random_lines('file.txt'):
print(line)

关于python - 从文件中检索 10 个随机行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18455589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com