编程语言
首页 > 编程语言> > python学习笔记(五) 依概率随机产生姓氏案例

python学习笔记(五) 依概率随机产生姓氏案例

作者:互联网

        生活中,不同的姓氏出现的频率大不相同。如赵、王、李等姓出现频率很高,而像东方、慕容这样的复姓却很少见到,今天我们就来在python中简单实现一下上述过程。

要求:姓氏全都按行保存在CNames中,越靠后的姓氏越少见。各行数组出现概率比为20:15:5:2:1,对应行数组为0-3行,4-8行,9-15行,16-20行,21-25行

CNames.txt文件包含内容如下图所示:
在这里插入图片描述

加载数据

	def load_file():
    text_data=[]
    with open('CName.txt','r',encoding='utf-8') as f:
        data=f.readlines()
        for line in data:
            tmp=line.split(';')
            text_data.append(tmp[:-1])
    return text_data

产生概率行数组

	probability_control=[
	    [0,1,2,3],
	    [4,5,6,7,8],
	    [9,10,11,12,13,14,15],
	    [16,17,18,19,20],
	    [21,22,23,24,25]
	]
	loop=[20,15,5,2,1]
	def probability_line(data:list,ranges:list):
    if len(data)==len(ranges):
        data=data.copy()
        count=0
        for loops in loop:
            for a in range(loops-1):
                data.append(data[count])
            count+=1
        return data
    else:
        print('长度不匹配')

产生随机姓氏

	import random
	def generator_line(data):
    name=load_file()
    line_combine=data[random.randrange(len(data))]
    line=line_combine[random.randrange(len(line_combine))]
    random_name=name[line][random.randrange(len(name[line]))]
    return random_name

全部代码:

	import random
	probability_control=[
	    [0,1,2,3],
	    [4,5,6,7,8],
	    [9,10,11,12,13,14,15],
	    [16,17,18,19,20],
	    [21,22,23,24,25]
	]
	loop=[20,15,5,2,1]
	def load_file():
	    text_data=[]
	    with open('CName.txt','r',encoding='utf-8') as f:
	        data=f.readlines()
	        for line in data:
	            tmp=line.split(';')
	            text_data.append(tmp[:-1])
	    return text_data
	   
	def probability_line(data:list,ranges:list):
	    if len(data)==len(ranges):
	        data=data.copy()
	        count=0
	        for loops in loop:
	            for a in range(loops-1):
	                data.append(data[count])
	            count+=1
	        return data
	    else:
	        print('长度不匹配')
	
	def generator_line(data):
	    name=load_file()
	    line_combine=data[random.randrange(len(data))]
	    line=line_combine[random.randrange(len(line_combine))]
	    random_name=name[line][random.randrange(len(name[line]))]
	    return random_name
	
	def main():
	    data=probability_line(probability_control,loop)
	    with open('random_name.txt','w') as f:
	        for i in range(10000):  # 随机产生10000个姓氏
	            name=generator_line(data)
	            f.write(name+'\n')
	
	if __name__=='__main__':
	    main() 

标签:name,python,random,笔记,姓氏,len,line,data,def
来源: https://blog.csdn.net/shine4869/article/details/104595674