在文件上打印随机名称

时间:2015-08-05 20:31:08

标签: python list file random

我想知道如何从文件中打印随机名称。基本上有3个文件,分别是姓氏,男性名字和女性名字。这些文件不仅仅包含名称。他们也有数字。以下是文件的示例:

    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

我希望输出打印出姓氏和名字(没有数字)这是我到目前为止的代码。它有效,但它打印出数字。

导入随机

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)

即使我将其修改为read2 [0] read1 [0] read3 [0],它也会打印掉字母。

J M
S H
E T
R I
A I
M H
J S
A I
M I
Y S

1 个答案:

答案 0 :(得分:0)

定义一个函数get_names(filename),它从文件中提取所有名称,例如:

def get_names(filename):
    with open(filename) as file:
        return [line.split(None, 1)[0] for line in file if line.strip()]

单独测试 ,然后在您的脚本中使用它,例如:

#!/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)))

此代码可能会生成重复的全名。要从群体中选择k 唯一随机元素,请改用random.sample()