导语

以前上英语课老师都会教哪些名字一听就知道是男生的,比如david、tom、jerry,然后angela、sophia一听就是女生的名字。当你以为所有名字一听就可以辨别男女的时候,你就想错了~就像中文里面“贾凡”,你以为是男生,其实是女生也说不定。这种难分性别的名字

其实很多呢~为了避免宝宝的性别和提前取好的名字冲突,很多准妈妈会给自己的孩子取一个中性的名字,不管男女都可以用哈哈哈~两全其美

​每个女孩子都希望自己的姓名能取的好听一点儿,也不希望经常跟男孩子名字撞名吧~想想一个班里面一个男生一个女生名字撞了多尴尬,如果名字偏女孩子一点儿,男生叫这个名字那可能就尴尬癌都犯了,相反也是!

当然,送大家一句经典台词抢救一下:“你不尴尬——尴尬的就是别人!“

哈哈哈!那下面就说到正题了哈:今天www.887551.com教大家编写一款根据中文名能猜测性别的一款界面化的小程序呢~

一、准备环节

本文是基于pyqt5的界面化小程序啦~

1.1 安装环境

python3、pycharm、pyqt5以及一些自带滴。

模块安装: pip install -i https://pypi.douban.com/simple/ +模块名

二、准备素材

素材的话就是界面化小程序的头像标志以及之前自己爬取准备的一份百家姓的数据csv数据。

三、开始敲代码

3.1 导入模块

import os
import csv
import sys
from pyqt5.qtgui import *
from pyqt5.qtwidgets import *

3.2 定义界面

self.setwindowtitle('诸子百家——姓名猜性别小程序')
        self.setwindowicon(qicon('data/3.png'))
        self.setfixedsize(400, 200)
        self.name_label = qlabel('中文姓名:')
        self.male_label = qlabel('男生概率:')
        self.female_label = qlabel('女生概率:')
        self.button = qpushbutton('预测')
        self.name_edit = qlineedit()
        self.male_edit = qlineedit()
        self.female_edit = qlineedit()
        self.grid = qgridlayout()
        self.grid.setspacing(12)
        self.grid.addwidget(self.name_label, 0, 0)
        self.grid.addwidget(self.male_label, 1, 0)
        self.grid.addwidget(self.female_label, 2, 0)
        self.grid.addwidget(self.name_edit, 0, 1)
        self.grid.addwidget(self.male_edit, 1, 1)
        self.grid.addwidget(self.female_edit, 2, 1)
        self.grid.addwidget(self.button, 0, 2)
        self.setlayout(self.grid)
        self.button.clicked.connect(lambda: self.predict(self.name_edit.text()))

3.3 预测性别

​def predict(self, name):
        def genderprob(name, probs, type_='male'):
            assert type_ in ['male', 'female']
            if type_ == 'male':
                p = self.male_total / self.total
                for c in name:
                    p *= probs.get(c, (0, 0))[0]
            else:
                p = self.female_total / self.total
                for c in name:
                    p *= probs.get(c, (0, 0))[1]
            return p
        for c in name:
            assert u'\u4e00' <= c <= u'\u9fa0'
        male_prob = genderprob(name, self.name_probs, 'male')
        female_prob = genderprob(name, self.name_probs, 'female')
        result = {'male': male_prob / (male_prob + female_prob), 'female': female_prob / (male_prob + female_prob)}
        self.male_edit.settext(str(result['male']))
        self.female_edit.settext(str(result['female']))
        return result

3.4 读取数据 

    def readcsv(self, csvpath='freqs.csv'):
        fp = open(csvpath, 'r', encoding='utf-8')
        csv_reader = csv.reader(fp)
        name_freqs = {}
        for idx, row in enumerate(csv_reader):
            if idx == 0: continue
            name_freqs[row[0]] = (row[1], row[2])
        return name_freqs

3.5 附完整的源码

'''
程序名称:
    根据中文名字推断性别
    源码基地:#806965976#
    csdn账号:顾木子吖
'''
import os
import csv
import sys
from pyqt5.qtgui import *
from pyqt5.qtwidgets import *
 
 
'''根据中文名字判断性别'''
class genderpredictor(qwidget):
    def __init__(self, parent=none, **kwargs):
        super(genderpredictor, self).__init__(parent)
        # 定义界面
        self.setwindowtitle('诸子百家——姓名猜性别小程序')
        self.setwindowicon(qicon('data/3.png'))
        self.setfixedsize(500, 500)
        self.name_label = qlabel('中文姓名:')
        self.male_label = qlabel('男生概率:')
        self.female_label = qlabel('女生概率:')
        self.button = qpushbutton('预测')
        self.name_edit = qlineedit()
        self.male_edit = qlineedit()
        self.female_edit = qlineedit()
        self.grid = qgridlayout()
        self.grid.setspacing(12)
        self.grid.addwidget(self.name_label, 0, 0)
        self.grid.addwidget(self.male_label, 1, 0)
        self.grid.addwidget(self.female_label, 2, 0)
        self.grid.addwidget(self.name_edit, 0, 1)
        self.grid.addwidget(self.male_edit, 1, 1)
        self.grid.addwidget(self.female_edit, 2, 1)
        self.grid.addwidget(self.button, 0, 2)
        self.setlayout(self.grid)
        self.button.clicked.connect(lambda: self.predict(self.name_edit.text()))
        # 模型初始化
        self.name_freqs = self.readcsv(os.path.join(os.getcwd(), 'data/freqs.csv'))
        self.male_total = 0
        self.female_total = 0
        for key, value in self.name_freqs.items():
            self.male_total += int(value[0])
            self.female_total += int(value[1])
        self.total = self.male_total + self.female_total
        self.name_probs = {}
        for key, value in self.name_freqs.items():
            self.name_probs[key] = (int(value[0])/self.male_total, int(value[1])/self.female_total)
    '''预测性别'''
    def predict(self, name):
        def genderprob(name, probs, type_='male'):
            assert type_ in ['male', 'female']
            if type_ == 'male':
                p = self.male_total / self.total
                for c in name:
                    p *= probs.get(c, (0, 0))[0]
            else:
                p = self.female_total / self.total
                for c in name:
                    p *= probs.get(c, (0, 0))[1]
            return p
        for c in name:
            assert u'\u4e00' <= c <= u'\u9fa0'
        male_prob = genderprob(name, self.name_probs, 'male')
        female_prob = genderprob(name, self.name_probs, 'female')
        result = {'male': male_prob / (male_prob + female_prob), 'female': female_prob / (male_prob + female_prob)}
        self.male_edit.settext(str(result['male']))
        self.female_edit.settext(str(result['female']))
        return result
    '''读取数据集'''
    def readcsv(self, csvpath='freqs.csv'):
        fp = open(csvpath, 'r', encoding='utf-8')
        csv_reader = csv.reader(fp)
        name_freqs = {}
        for idx, row in enumerate(csv_reader):
            if idx == 0: continue
            name_freqs[row[0]] = (row[1], row[2])
        return name_freqs
 
 
'''run'''
if __name__ == '__main__':
    app = qapplication(sys.argv)
    client = genderpredictor()
    client.show()
    sys.exit(app.exec_())

四、效果展示

4.1  姓名:顾雪 效果part 1

是不是听这个名字就知道是女生吖~测一测之后果然女生取这个名字的概率高出一截儿哈!

4.2 姓名:李志 效果part 2

总结

好啦!一款简单的猜猜猜小程序就出炉了,偷偷拿自己的名字试试看吧~哈哈哈 不告诉别人.jpg

以上就是基于python编写一个根据姓名测性别的小程序的详细内容,更多关于python姓名测性别的资料请关注www.887551.com其它相关文章!