from random import choice
choice(your_list)
example:
from random import choice
my_list = ["apples", "oranges", "pears"]
print(choice(my_list)[0])
Answer from James on Stack Overflowfrom random import choice
choice(your_list)
example:
from random import choice
my_list = ["apples", "oranges", "pears"]
print(choice(my_list)[0])
You can randint to get a random index for the list
your_list = ['Hello','world']
from random import randint
print(your_list[randint(0,len(your_list)-1)])
Picking a Random Word from a list in python? - Stack Overflow
Random word generator- Python - Stack Overflow
Generating a random word from an array
Random words generate using python - Stack Overflow
Reading a local word list
If you're doing this repeatedly, I would download it locally and pull from the local file. *nix users can use /usr/share/dict/words.
Example:
word_file = "/usr/share/dict/words"
WORDS = open(word_file).read().splitlines()
Pulling from a remote dictionary
If you want to pull from a remote dictionary, here are a couple of ways. The requests library makes this really easy (you'll have to pip install requests):
import requests
word_site = "https://www.mit.edu/~ecprice/wordlist.10000"
response = requests.get(word_site)
WORDS = response.content.splitlines()
Alternatively, you can use the built in urllib2.
import urllib2
word_site = "https://www.mit.edu/~ecprice/wordlist.10000"
response = urllib2.urlopen(word_site)
txt = response.read()
WORDS = txt.splitlines()
Solution for Python 3
For Python3 the following code grabs the word list from the web and returns a list. Answer based on accepted answer above by Kyle Kelley.
import urllib.request
word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()
Output:
>>> words
['a', 'AAA', 'AAAS', 'aardvark', 'Aarhus', 'Aaron', 'ABA', 'Ababa',
'aback', 'abacus', 'abalone', 'abandon', 'abase', 'abash', 'abate',
'abbas', 'abbe', 'abbey', 'abbot', 'Abbott', 'abbreviate', ... ]
And to generate (because it was my objective) a list of 1) upper case only words, 2) only "name like" words, and 3) a sort-of-realistic-but-fun sounding random name:
import random
upper_words = [word for word in words if word[0].isupper()]
name_words = [word for word in upper_words if not word.isupper()]
rand_name = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])
And some random names:
>>> for n in range(10):
' '.join([name_words[random.randint(0,len(name_words))] for i in range(2)])
'Semiramis Sicilian'
'Julius Genevieve'
'Rwanda Cohn'
'Quito Sutherland'
'Eocene Wheller'
'Olav Jove'
'Weldon Pappas'
'Vienna Leyden'
'Io Dave'
'Schwartz Stromberg'
As the title says it, I'm dropping here the code to get a random word from an array as it hasn't been mentioned on any forum
Here is the code:
#include<stdio.h>
#include<stdlib.h>
int main(){
int x=0;
int y;
char words[][10]={"cat","dog","giraffe","fly"};
for(int i=0;i<10;i++){
y=rand()%4+1;
}
printf("%s ",words[y]);
return 0;
}
This code gives also a random number, which is "y".
If you run this code you might get the same answers twice or maybe more but that is because the array is small but the more your array contains more words, the chance of getting the same word decreases.
Also in case you want to enlarge the array just change the number "4" to the number of elements in the array.
Have a nice day everyone.
Based on an answer to the question about generating discrete random variables with specified weights, you can use numpy.random.choice to get 20 times faster code than with random.choice:
from numpy.random import choice
sample = choice(['apple','orange','mango'], p=[0.4, 0.3, 0.3], size=1000000)
from collections import Counter
print(Counter(sample))
Outputs:
Counter({'apple': 399778, 'orange': 300317, 'mango': 299905})
Not to mention that it is actually easier than "to build a list in the required proportions and then shuffle it".
Also, shuffle would always produce exactly 40% apples, 30% orange and 30% mango, which is not the same as saying "produce a sample of million fruits according to a discrete probability distribution". The latter is what both choice solutions do (and the bisect too). As can be seen above, there is about 40% apples, etc., when using numpy.
The easiest way is to build a list in the required proportions and then shuffle it.
>>> import random
>>> result = ['apple'] * 40 + ['orange'] * 30 + ['mango'] * 30
>>> random.shuffle(result)
Edit for the new requirement that the count is really 1,000,000:
>>> count = 1000000
>>> pool = ['apple'] * 4 + ['orange'] * 3 + ['mango'] * 3
>>> for i in xrange(count):
print random.choice(pool)
A slower but more general alternative approach is to bisect a cumulative probability distribution:
>>> import bisect
>>> choices = ['apple', 'orange', 'mango']
>>> cum_prob_dist = [0.4, 0.7]
>>> for i in xrange(count):
print choices[bisect.bisect(cum_prob_dist, random.random())]
» pip install random_word
I want to generate a random word of a specific length. I found a python module called random-word and this is my code.
from random_word import RandomWords
r = RandomWords()
# Return a single random word
r.get_random_word()
result = None
while result is None:
try:
word1 = r.get_random_word()
print (word1)
if len(word1) == 5:
result = True
except:
print ('There was a problem')
# other code that uses result but is not involved in getting it
print (word1)
print (len(word1))It works perfectly fine, but it's very slow. It takes about 10 to 15 seconds to run until it finds a word of that length. Does anybody have a better way of doing this? Another way I thought was to maybe have a dictionary file and iterate through that. The reason I don't like that approach is I don't really like the idea of having to have a file on the machine. Also if it iterates through the file it won't be random.
Any suggestions appreciated.
Thanks
random.choice(words) * 5 executes random.choice only once and then multiplies the result by five, causing the same string to be repeated.
>>> import random
>>> words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
>>> print ''.join(random.choice(words) for _ in range(5))
applesomethinghellohellolalala
If you don't want the words from your original list to be repeated, then you could use sample.
import random as rn
words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
word = ''.join(rn.sample(words, 5))
Result:
>>> word
'yeahhellosomethingapplenope'