简体   繁体   English

Python-打开TXT,随机化,另存为新文件

[英]Python - Open TXT, Randomize, Save as New File

I've been messing around with randomizing in python for awhile now but for some reason I'm stuck here. 我一直在混乱中使用python进行随机化,但是由于某种原因我被困在这里。 Maybe it's just too late at night... 也许到了晚上太晚了...

Anyway, I'm looking for a quick an easy method in Python to; 无论如何,我正在寻找一种快速简便的Python方法;

  • Open TXT File 打开TXT文件
  • Randomize Lines 随机行
  • Save as new TXT File 另存为新的TXT文件

I'm feeling kinda dumb here... Any help is appreciated! 我在这里感觉有点愚蠢...感谢您的帮助! Thanks! 谢谢!

Use random.shuffle to randomize a sequence: 使用random.shuffle随机化序列:

import random

with open('filename', 'rb') as infile:
    lines = infile.readlines()

random.shuffle(lines)

with open('newfilename', 'wb') as outfile:
    outfile.writelines(lines)

Edit: The method of shuffling suggested in the other answer is wrong. 编辑:在另一个答案中建议的改组方法是错误的。 See the comments and the links therein. 请参阅评论及其中的链接。 Here is a more correct example of a shuffle: 这是随机播放的更正确示例:

end = len(lines) - 1
for i in range(end + 1):
    choice = random.randint(i, end)
    lines[i], lines[choice] = lines[choice], lines[i]

After this shuffle, assuming perfect randomness from randint , the position of a line is completely uncorrelated with its position before the shuffle. 随机混randint ,假设randint完全随机性,则randint的位置与混洗前的位置完全不相关 Using the naive algorithm in the other answer, that isn't the case. 在另一个答案中使用天真的算法,不是这种情况。 The two shuffles both take the same number of operations. 这两个混洗都执行相同数量的操作。

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

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