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

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])

欺骗并返回(示例):

升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的更多信息。

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

10-11 22:32
查看更多