Simple random name generator in Python
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 t开发者_Go百科hen 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?
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
You'll have to read through the entire file at some point, unless you know beforehand how many prefixes and suffixes there are. Since I assume you don't, or that it can change and you don't want to maintain a number for storing that, you'll have to read through the file, and readline() is a good way of doing that.
However, you can preprocess your text file so that it uses another format, such as a pickle file. In other words, read the text file into a dictionary, and pickle that dictionary. The dictionary might look something like this:
dic = {'prefixes': ['Ae' ,'di', ...],
'suffixes': ['dar', 'kil', ...]}
From the lenght of the arrays you can then determine what the maximum random number is. It should be more efficient than reading an entire file line-for-line each time. And if not, at least it's a bit more elegant solution.
Modified @eumiro's script:
#!/usr/bin/env python
import fileinput
import random
import re
from collections import defaultdict
partname = ''
parts = defaultdict(list)
for line in fileinput.input():
line = line.rstrip()
if line.startswith('[') and re.match(r'\[part\d+\]', line):
partname = line
else:
parts[partname].append(line)
parts_list = list(map(parts.get, sorted(parts)))
for _ in range(10):
print(''.join(map(random.choice, parts_list)))
Output
Famglar
Famkil
Didar
Ditres
Aedar
Famglar
Ditres
Famtres
Ditres
Modar
I once found a unique, pseudo name generator I used quite often at a website called domainhole, but then security warnings and alerts popped every time I tried to visit the site. So I wrote a script to do the same thing it was doing.
import random
vowels = [97,101,105,111,117]
consonants = [98,99,100,102,103,104,106,107,108,109,110,112,113,114,115,116,118,119,120,121,122]
def get_character(seed):
match seed:
case 'L':
return chr(random.randint(97,122))
case 'C':
return chr(consonants[random.randint(0,len(consonants)-1)])
case 'V':
return chr(vowels[random.randint(0,len(vowels)-1)])
case _:
return -1
# enter custom values here: C for consonants, V for vowels, and L for all letters
pseudonym_array = ['C','L','V','L']
pseudonym = ''
for i in range(len(pseudonym_array)):
pseudonym += get_character(pseudonym_array[i])
print(pseudonym)
精彩评论