从序列x中随机选择y条数据作为文本:
# -*- coding:utf-8 -*-
##随机挑选部分内容
# encoding:utf-8
import random
from random import randint
oldf = open('select_amigo.txt', 'r') ###1000行
newf = open('select_amigo222.txt', 'w') ###挑选400行
n = 0
resultList = random.sample(range(0, 1000), 400) # sample(x,y)函数的作用是从序列x中,随机选择y个不重复的元素。
lines = oldf.readlines()
for i in resultList:
newf.write(lines[i])
oldf.close()
newf.close()
本文介绍了一种使用Python的random模块来从大文件中随机挑选特定数量行的方法。通过使用random.sample函数,可以确保所选行的随机性和独立性,这对于数据分析、抽样调查等场景非常有用。
490

被折叠的 条评论
为什么被折叠?



