I was wondering how to print random names from a file. Basically there are 3 files which are surnames,male names and female names. The files have more than just the names. They have numbers as well. Here's an example of what the file looks like:
SMITH 1.006 2,501,922 1
JOHNSON 0.81 2,014,470 2
WILLIAMS 0.699 1,738,413 3
JONES 0.621 1,544,427 4
BROWN 0.621 1,544,427 5
DAVIS 0.48 1,193,760 6
MILLER 0.424 1,054,488 7
WILSON 0.339 843,093 8
MOORE 0.312 775,944 9
I want the output to print out a last name and first name(no numbers) Here is my code so far. It works but it prints out the numbers.
import random
def random_names(surname,male_names,female_names,integer):
names1 = open('surnames.txt', 'r')
names2 = open('malenames.txt', 'r')
names3 = open('femalenames.txt', 'r')
read1=names1.read().split()
read2=names2.read().split()
read3=names3.read().split()
gender_options = ('male', 'female')
count = 0
while count<integer:
gender_pick=random.choice(gender_options)
if gender_pick == 'male':
first_name=random.choice(read2)
elif gender_pick == 'female':
first_name=random.choice(read3)
last_name=random.choice(read1)
print (first_name,last_name)
count = count+1
random_names('surnames.txt', 'malenames.txt', 'femalenames.txt',10)
Even when I modify it to read2[0] read1[0] read3[0], it just prints out the letters.
J M
S H
E T
R I
A I
M H
J S
A I
M I
Y S
Define a function get_names(filename)
that extracts all names from a file eg:
def get_names(filename):
with open(filename) as file:
return [line.split(None, 1)[0] for line in file if line.strip()]
Test it separately and then use it in your script eg:
#!/usr/bin/env python
import itertools
import random
def generate_random_names(surnames, male_names, female_names,
choose=random.choice):
while True:
# make male/female names equally likely
forename = choose(choose([male_names, female_names]))
yield forename, choose(surnames)
name_lists = map(get_names, ['surnames.txt', 'malenames.txt', 'femalenames.txt'])
fullnames = generate_random_names(*name_lists)
print(list(itertools.islice(fullnames, 50)))
This code may generate duplicate full names. To choose k
unique random elements from a population use random.sample()
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.