开发者

modify program of generation for saving words in list and choosing them with random.choice()

开发者 https://www.devze.com 2023-04-11 14:17 出处:网络
How to modify program of generation for saving words in list and choosing them with random.choice() previously doimport random?

How to modify program of generation for saving words in list and choosing them with random.choice() previously do import random?

where is mistake? its not working correct

def generate_model(cfdist,word,num=15):
    for i in range(num):
        word=random.choice.im_class(cfdist
                        [word].keys())


>>> ge开发者_开发问答nerate_model(cfd,'living')


There is all kinds of weird stuff going on with that code:

def generate_model(cfdist,word,num=15):

You use word as the key to look up in the dictionary.

    word=

Then you change it? Are you intentionally chaining the result of one random lookup as the key for the next lookup?

random.choice

If you're intentionally chaining, this is right, but if you want a bunch of words from the same dict you want random.sample.

.im_class(

This is completely unnecessary. Just call it like random.choice(. Look at the examples in the random docs

cfdist[word]

You're getting the value in cfdist with the key equal to the value of word passed in (in this case, living) the first time, then the key is equal to the result of the choice after that. Is that what you intended?

.keys())

This will work, if each value in cfdist is a dict.

Now, you say you want

for saving words in list

But since I'm not sure what exactly you want, I'll give two examples. The first, I'll just aggregate the words, but not change anything else:

def generate_model(cfdist,word,num=15):
    words = []
    # you can add the starting word with words.append(word) here if you want
    for i in range(num):
        word=random.choice(cfdist[word].keys())
        words.append(word)
    return words

The second, I'll assume you just want 15 random words from the dict with no repetitions:

def generate_model(cfdist,word,num=15):
    return random.sample(cfdist[word].keys(), num)

Then either way call it as

>>> words = generate_model(cfd,'living')

to get the list of words.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号