I have a text file containing first and last 'syllables', demarcated with [part1] and [part2]:
[part1] Ae Di Mo Fam [part2] dar kil glar tres
All I want to do is pick a random line, between [part1] and [part2], and then another random line between [part2] and the end of the file, and concatenate the two together (e.g. "Aedar", "Moglar") to create random names.
However I am unsure how to parse the text file effectively with readline(). Is there a better way than scanning through each line sequentially, and storing all of them in a list from whence I can pick a random element?
sample() Method to Randomly Select Elements From a List. Python has a built-in function called random. sample(). The random module contains the random.
So it is better to know how to generate random numbers in Python. For a random number generator, we will use a random package of python, which is inbuilt in python. It has many inbuilt functions inside it, which can be used to generate random numbers based on our requirements.
However to generate random names a better solution is to use for example the module " names " created by Trey Hunner: To install names with pip If you work with anaconda just do:
The random name picker relies on the cumulative frequencies listed in the included Census data files. Here’s the steps that are taken: 1. A random floating point number is chosen between 0.0 and 90.0 2. Name file lines are iterated through until a cumulative frequency is found that is less than the randomly generated number 3.
The secrets module is the most secure method to generate random numbers and finds excellent use in cryptography. One application of this module is to create strong, secure random passwords, tokens etc.
Serialize (pickle) a dictionary to a file instead.
Example:
# create the dict and save it to a file
d={
'part1':[
'Ae',
'Di',
'Mo',
'Fam',],
'part2':[
'dar',
'kil',
'glar',
'tres',],
}
import pickle
f=open('syllables','w')
pickle.dump(d,f)
f.close()
# read the dict back in from the file
f1=open('syllables','r')
sd=pickle.load(f1)
f1.close()
import random
first_part=sd['part1'][random.randint(0,len(sd['part1'])-1)]
second_part=sd['part2'][random.randint(0,len(sd['part2'])-1)]
print '%s%s'%(first_part,second_part)
import random
parts = {}
with open('parts.txt', 'r') as f:
currentList = []
for line in f.readlines():
line = line.strip()
if line.startswith('[') and line.endswith(']'):
currentList = []
parts[line[1:-1]] = currentList
else:
currentList.append(line.strip())
for i in xrange(10):
print ''.join(random.choice(parts[partName]) for partName in sorted(parts))
returns (randomly):
Aekil
Didar
Mokil
Mokil
Moglar
Moglar
Diglar
Famdar
Famdar
Modar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With