使用数组生成随机文本

Jul*_*lia 10 python arrays

我试图使用我获得的字母频率生成随机文本.首先,我成功完成以下代码:

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')
    ....
Run Code Online (Sandbox Code Playgroud)

这直到字母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]')
Run Code Online (Sandbox Code Playgroud)

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

eum*_*iro 17

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])
Run Code Online (Sandbox Code Playgroud)

诀窍并返回(示例):

升wefboethol gsplotfoh UA onpedefh dnolnairnioeiegehhecaworonnfmeuej dsiauhpbfttwcknal ateof AP cgbr sunnee leseaeeecltaiaurùOEN vxntgsoio kdeniei OT DF HTR dcencrsrrfp bwelsuoaslrnr HEH EE TPT oeejaldeatcto音响AU idimiadmgglral OM iaielbtnt ES OE shlspudwdfrrsvol oo的我tlwh DRI swhsnloai p swlooi WBEンsshth nsawtnrqsud MTW diit pnerřnitmah todf zcsehma hl e ros ctee toiouinn i hl hlonphioe nh gan ho heein itrgeylftn epaacrmanhe

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

bisect.bisect(list, value)获取一个排序列表和一个值,并告诉它应该放在哪里.更多关于bisect.