20171024 - djangolesson - 2 - 2 获取随机姓名

1. 第一个文件: random_name1.py

# encoding: utf-8  


""" 
@author: 李绍俊
@license: Apache Licence  
@contact: [email protected]
@file: random_name1.py 
@time: 2017/10/24 15:49 
"""

import random

a1 = ['赵','钱','孙','李']
a2 = ['玉','明','龙','芳','军','玲']
a3 = ['','立','玲','','国']


def get_random_name():
    name = random.choice(a1)+random.choice(a2)\
           +random.choice(a3)
    return name

2. 第二个文件: random_name2.py

# encoding: utf-8  


""" 
@author: 李绍俊
@license: Apache Licence  
@contact: [email protected]
@file: random_name2.py 
@time: 2017/10/24 16:13 
"""


import random
import string

myPath = 'C:\\djangolesson\\ch02\\'
def get_last_names():
    last_names = []

    with open(myPath+"百家姓.txt", 'r') as f:
        for row in f:
            last_names.append(row.strip().split('    ')[1])

    return last_names


def get_first_names():
    str_fn = ""

    with open(myPath+"名.txt", 'r') as f:
        for row in f:
            str_fn += row.strip()

    str_fn = str_fn.replace("'", "")
    str_fn = str_fn.replace(" ","")


    return str_fn.split(',')


def random_words(size=1, chars=string.ascii_letters+string.digits):
    return ''.join(random.choice(chars) for _ in range(size))


def get_random_name():
    lns = get_last_names()
    fns = get_first_names()

    ln = random_words(1, lns)

    fn = random_words(random.randint(1,2),fns)

    return ln+fn

for _ in range(20):
    print(get_random_name())

你可能感兴趣的:(20171024 - djangolesson - 2 - 2 获取随机姓名)