lundi 9 mai 2016

Better way to get random choice instead of random.choice (python)

I am trying to get my program to return a random word from a list within a dictionary. It seems to be working fine, but when I enter in a longer phrase i get the error:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/random.py", line 253, in choice
    i = self._randbelow(len(seq))
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/random.py", line 230, in _randbelow
    r = getrandbits(k)          # 0 <= r < 2**k
ValueError: number of bits must be greater than zero

During handling of the above exception, another exception occurred:

    s = random.choice(thesaurus[x]).upper() if x in thesaurus else x
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/random.py", line 255, in choice
    raise IndexError('Cannot choose from an empty sequence')
IndexError: Cannot choose from an empty sequence

Which seems to be related to the random.choice I am using - I was wondering if there was a better way to get a random word from a list of strings instead of random.choice(). My code is below:

import random

thesaurus = {}
with open('thesaurus.txt') as input_file:
    for line in input_file:
        synonyms = line.split(',')
        thesaurus[synonyms[0]] = synonyms[1:]

print ("Total words in thesaurus: ", len(thesaurus))

# input
phrase = input("Enter a phrase: ")

# turn input into list
part1 = phrase.split()
part2 = list(part1)


# trouble section

newlist = []
for x in part2:
    s = thesaurus[x].pop() if x in thesaurus else x
    s = random.choice(thesaurus[x]).upper() if x in thesaurus else x # this is what i want to replace
    newlist.append(s)


newphrase = ' '.join(newlist)

print(newphrase)




Aucun commentaire:

Enregistrer un commentaire