gpt4 book ai didi

python - 使用数组生成随机文本

转载 作者:太空狗 更新时间:2023-10-29 18:20:43 24 4
gpt4 key购买 nike

我正在尝试使用我获得的字母频率生成随机文本。首先,我使用以下代码成功了:

for i in range(450):
outcome=random.random()
if 0<outcome<0.06775:
sys.stdout.write('a')
if 0.06775<outcome<0.07920:
sys.stdout.write('b')
if 0.07920<outcome<0.098:
sys.stdout.write('c')
....

直到字母 z 和空格键。这给了我 50 多行代码,我想使用数组获得相同的结果。

到目前为止我有:

f_list = [0, 0.06775, 0.08242, 0.10199, 0.13522, 0.23703, 0.25514, 0.27324, 0.32793, 0.38483, 0.38577, 0.39278, 0.42999, 0.45023, 0.50728, 0.56756, 0.58256, 0.58391, 0.62924, 0.68509, 0.7616, 0.78481, 0.79229, 0.81161, 0.81251, 0.82718, 0.82773, 0.99998]
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ']

import random
import sys

for i in range(25):
outcome=random.random()
if f_list[i]<outcome<f_list[i+1]:
sys.stdout.write('alphabet[i]')

但它不能正常工作,因为范围现在似乎与数组有关,而不是我想要的迭代次数。输出为空白。

最佳答案

import random
import sys
import bisect

f_list = [0, 0.06775, 0.08242, 0.10199, 0.13522, 0.23703, 0.25514, 0.27324, 0.32793, 0.38483, 0.38577, 0.39278, 0.42999, 0.45023, 0.50728, 0.56756, 0.58256, 0.58391, 0.62924, 0.68509, 0.7616, 0.78481, 0.79229, 0.81161, 0.81251, 0.82718, 0.82773, 0.99998]
alphabet = 'abcdefghijklmnopqrstuvwxyz '

for i in xrange(450):
sys.stdout.write(alphabet[bisect.bisect(f_list, random.random()) - 1])

成功并返回(示例):

l wefboethol gsplotfoh ua onpedefh dnolnairnioeiegehhecaworonnfmeuej dsiauhpbfttwcknal ateof ap cgbr sunnee leseaeeecltaiaur u oen vxntgsoio kdeniei ot df htr dcencrsrrfp bwelsuoaslrnr heh ee tpt oeejaldeatcto fi a u idimiadmgglral o m iaielbtnt es oe shlspudwdfrrsvol oo i tlwh d r i swhsnloai p swlooi wbe nn sshth nsawtnrqsud mtw diit pner r nitmah todf zcsehma hl e ros ctee toiouinn i hl hlonphioe nh gan ho heein itrgeylftn epaacrmanhe

alphabet 也可以定义为一个简单的字符串(访问它的元素 - 单个字符 - 就像列表一样)

bisect.bisect(list, value) 接受一个排序列表和一个值,并告诉应该将这个值放在两者之间的位置。更多关于 bisect .

关于python - 使用数组生成随机文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8589297/

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