在python中生成具有一定长度的随机字符串行的最快方法

2024-10-04 05:22:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在寻找一种方法来生成,例如,每行随机生成一个6个字符的字符串

问题是,我觉得我的代码很慢:

import random
import string
import threading

length = int(input("length:"))


def MainCode():
    while 1 == 1:
        letters = string.ascii_lowercase
        actual_random = ''.join(random.choice(letters) for i in range(length))
        print(actual_random)
        towrite = open("TestSpeed.txt","a")
        towrite.write(actual_random + "\n")
        towrite.close()

虽然代码可以工作,但对于我想要的东西来说速度非常慢

我研究过这个线程,这段代码速度非常快,工作起来令人惊讶:Fastest method to generate big random string with lower Latin letters

它只打印到控制台,而不是写入文件(我不确定这是否会影响速度)

守则:

import os
import sys

nbytes = 256
nletters = 26
naligned = nbytes - (nbytes % nletters)
tbl = bytes.maketrans(bytearray(range(naligned)),
                      bytearray([ord(b'a') + b % nletters
                                 for b in range(naligned)]))
bytes2delete = bytearray(range(naligned, nbytes))
R = lambda n: os.urandom(n).translate(tbl, bytes2delete)

def write_random_ascii_lowercase_letters(write, n):
    """*write* *n* random ascii lowercase letters."""    
    while n > 0:
        # R(n) expected to drop `(nbytes - nletters) / nbytes` bytes
        # to compensate, increase the initial size        
        n -= write(memoryview(R(n * nbytes // naligned + 1))[:n])

write = sys.stdout.buffer.write
write_random_ascii_lowercase_letters(write, 1000000)

问题是,我真的一件事都不明白,只是有点不明白,但主要的东西什么都不懂 我试着搜索其他更简单的方法,但找不到任何方法,而且youtube视频也没有多大帮助

我要做的是生成一个包含X行的文件,每行有X个字符长,我考虑添加选择字符串中包含哪些字符的功能(下划线、大写、小写等),但首先我想知道代码在做什么,这样我才能正确地执行

一般来说,我对编程和Python有点陌生,所以对于任何明显的错误,我深表歉意


Tags: 方法代码importstringasciirangerandomlength