Nig*_*igu 26 python random vim
一切都在标题中.我想知道是否有人知道快速和合理的内存需求随机混合300万行文件的所有行的方式.我想用简单的vim命令是不可能的,所以任何使用Python的简单脚本都是如此.我使用随机数生成器尝试使用python,但没有设法找到一个简单的方法.
Joh*_*ica 42
在Python中只需几秒钟:
>>> import random
>>> lines = open('3mil.txt').readlines()
>>> random.shuffle(lines)
>>> open('3mil.txt', 'w').writelines(lines)
Run Code Online (Sandbox Code Playgroud)
S.L*_*ott 31
import random
with open('the_file','r') as source:
data = [ (random.random(), line) for line in source ]
data.sort()
with open('another_file','w') as target:
for _, line in data:
target.write( line )
Run Code Online (Sandbox Code Playgroud)
应该这样做.除非线路是巨大的(超过512个字符),否则300万行将适合大多数机器的内存.
Dra*_*ag0 19
我刚刚在一个有4.3M行的文件上尝试了这个,最快的是Linux上的'shuf'命令.像这样使用它:
shuf huge_file.txt -o shuffled_lines_huge_file.txt
Run Code Online (Sandbox Code Playgroud)
完成需要2-3秒.